PEP 484 class return type checking

I have a function in python that returns a class instead of an instance. How to indicate that the return value is a subclass of a particular type?

In the following example, I set the return value as a type, but I would also like to indicate that the type has all the BaseClass attributes:

from typing import Dict, Any

def class_constructor(name: str, attrs: Dict[str, Any]) -> type
    ConstructedClass = type(name, (BaseClass,), attrs)
    return ConstructedClass

class BaseClass: ...

I can't say (...) -> BaseClass, as this points to an instance of BaseClass, not BaseClass.

To answer my own question, it looks like a problem with python / typing # 107 . At the moment, the best solution is:

from typing import Dict, Any

class BaseClass: ...

def class_constructor(name: str, attrs: Dict[str, Any]) -> Callable[Any, BaseClass]
    ConstructedClass = type(name, (BaseClass,), attrs)
    return ConstructedClass

If you know your signature __init__, you can use it instead Anyof Callable[Any, ...].

When support is added Type[T], the solution will be:

 from typing import Dict, Any

class BaseClass: ...

def class_constructor(name: str, attrs: Dict[str, Any]) -> Type[BaseClass]
    ConstructedClass = type(name, (BaseClass,), attrs)
    return ConstructedClass
+4
1

, , BaseClass .

 class BaseClassMeta(type):
     pass

 class BaseClass(metaclass=BaseClassMeta):
     ...

 def class_constructor(name: str, attrs: Dict[str, Any]) -> BaseClassMeta
     ConstructedClass = BaseClassMeta(name, (BaseClass,), attrs)
     return ConstructedClass
0

All Articles