How to specify typings for dynamic fields similar

2019-07-30 21:50发布

问题:

For example:

# field base class
class F:
    pass


# represent integer
class AF(F):
    pass


# represent string
class BF(F):
    pass


class M:
    a = AF()
    b = BF()

    def __init__(self):
        pass  # generate dynamic attrs based on specified static attrs


m = M()
# m.a should have inferred type integer

Maybe it is just IDE (PyCharm) feature with all these type hint, and this feature is hard-bind to django's Model class?

回答1:

Django's Model class has fields that explicitly check the type of the field as well as database migrations to add those types to the DB. If you want to use static types in python, consider using MyPy to annotate your functions and variables.