langlauf.io
langlauf.io

Reputation: 3201

Mypy: How to create an alias type with all classes from a module

I have a module foothat defines a lot of classes, e.g.

class A():
  ...
class B():
 ...
class C():
 ...
...

I would like to create a "foo type" alias comprising all these classes, i.e.

my_foo_type = Union[A, B, C, ...]

Yet, there are so many classes that I don't want to type them but have programmatic solution. I access to all classes defined in the module via

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print(obj)

How can I connect this with the type alias?

Upvotes: 3

Views: 531

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46843

I don't think it's possible. I don't know what you want to do with your classes but depending on your use case, you could:

  1. make your classes subclasses of a base class (it may also improve the design of your module);
  2. use an external script that will generate the type variable for you (and run this script each time you add or remove a class in your module);
  3. something else :)

Upvotes: 1

Related Questions