Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

Description

@DylannCordel

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]")

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions