Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhance the comprehension of the __new__ method of a metaclass #11398

Closed
DylannCordel opened this issue Oct 28, 2021 · 1 comment · Fixed by #11420
Closed

enhance the comprehension of the __new__ method of a metaclass #11398

DylannCordel opened this issue Oct 28, 2021 · 1 comment · Fixed by #11420
Labels

Comments

@DylannCordel
Copy link

DylannCordel commented Oct 28, 2021

Feature

The __new__ method of a Metaclass should be hinted as returning a specific Type.

Pitch

class MyPool:
    registry: Dict[str, Type[MyAbstractClass]] = {}
    
    @classmethod
    def register(cls, the_class):
        cls.registry[the_class.__name__] = the_class

class MyMetaClass(type):
    def __new__(cls, name, bases, attrs) -> Type[MyAbstractClass]:
        if not bases:
            return super().__new__(name, bases, attrs)
        new_class = super().__new__(name, bases, attrs)
        # do something with new_class. in my case:
        MyPool.register(new_class)
        return new_class

class MyAbstractClass(metaclass=MyMetaClass):
    pass

class MyRealClass(MyAbstractClass):
    pass

Currently, mypy will say: "__new__" must return a class instance (got "Type[MyAbstractClass]")

@sobolevn
Copy link
Member

sobolevn commented Oct 31, 2021

Great catch!

Minimal example:

from typing import Type

class MyMetaClass(type):
    def __new__(cls, name, bases, attrs) -> Type['MyClass']:
        pass

class MyClass(metaclass=MyMetaClass):
    pass

Error:

out/ex.py:4: error: "__new__" must return a class instance (got "Type[MyClass]")

PR is on its way.

JukkaL pushed a commit that referenced this issue Nov 1, 2021
…1398 (#11420)

Closes #11398

Now cases like 

```python
from typing import Type

class MyMetaClass(type):
    def __new__(cls, name, bases, attrs) -> Type['MyClass']:
        pass

class MyClass(metaclass=MyMetaClass):
    pass
```

will pass.
tushar-deepsource pushed a commit to DeepSourceCorp/mypy that referenced this issue Jan 20, 2022
…thon#11398 (python#11420)

Closes python#11398

Now cases like 

```python
from typing import Type

class MyMetaClass(type):
    def __new__(cls, name, bases, attrs) -> Type['MyClass']:
        pass

class MyClass(metaclass=MyMetaClass):
    pass
```

will pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants