using __new__ with type(x: T) resolvestype(x: T) as being of type type
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
The following code passes a MyPy check with flying colors:
from typing import TypeVar, Any
T = TypeVar("T", bound=Any)
def this_one_works(x: T) -> T:
res = x.__new__(type(x))
return res
But the following does not:
from typing import TypeVar, Any
T = TypeVar("T", bound=Any)
def this_one_not_so_much(x: T) -> T:
res = type(x).__new__(type(x))
return res
Instead it seems to resolve type(x) as <class 'type'> when used with __new__() and complains about missing arguments:
test.py:5: error: No overload variant of "new" of "type" matches argument type "Type[T]"
test.py:5: note: Possible overload variants:
test.py:5: note: def new(cls, cls: Type[type], o: object) -> type
test.py:5: note: def new(cls, cls: Type[type], name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type
Found 1 error in 1 file (checked 1 source file)
Is this expected behavior, or is it resolving incorrectly in the second case?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the two code snippets from the issue through mypy and comparing how type(x) and x.new are inferred. Trace the type-checking path for type(x).new and determine whether the reported resolution is expected; done means establishing the intended behavior and documenting or testing the result.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100