python / python/typing

Allow to use function objects as singletons

Open
#668 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

I was trying to create some stubs for lxml library, but I encountered a function that depending on a function object it gets (as in specific function object - checked with identity check) only finds objects of specific type.

Here's a very simplified mock-up of it so that you can get some idea on what I mean (the typing for arg argument in the find function is incorrect and that's what I want to be able to type hint in some way):

from typing import Union

class _Element: ...

def Element() -> _Element: ...

class _Comment: ...

def Comment() -> _Comment: ...

def find(arg: Union[Element, Comment]) -> Union[_Element, _Comment]:
    if arg is Element:
        # only find _Element objects
    elif arg is Element:
        # only find _Comment objects

# this function should only accept `Element` and `Comment` function object 
find(arg=Element)

So basically those functions serve as a singletons. Unfortunately typing.Union only allows Enums to work as singletons.

I am not entirely sure if this should be supported, usually the code could just be adjusted to use Enums, but in this case it will be used for type stubs so the code can't be edited. And to be honest, I am not sure if the code really needs editing in that case as if I didn't need typing for that library, I would say it's actually quite intuitive to use these factory functions as arguments in this case.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the factory-function singleton example and the comparison with Enum singletons in issue #668. No implementation files or tests are named in the issue, so first identify where typing represents singleton values and how function objects are currently handled. Done means establishing whether these function objects can be accepted and represented distinctly in type hints, with coverage for the Element/Comment-style case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.