Basically what you want is to dynamically modify the type hints in a class.
You can achieve that by modifying the annotations__ property of the class like so:
from typing import get_type_hints
class ModuleA:
"""This is a reusable element to compose larger designs with"""
class ModuleB:
"""Another reusable element"""
class MyDesign:
a: ModuleA
b0: ModuleA
b1: ModuleA
b2: ModuleA
if __name__ == '__main__':
print(get_type_hints(MyDesign))
for i in range(2):
MyDesign.__annotations__[f"b{i}"] = ModuleB
print(get_type_hints(MyDesign))
result of running this code:
{'a': <class '__main__.ModuleA'>, 'b0': <class '__main__.ModuleA'>, 'b1': <class '__main__.ModuleA'>, 'b2': <class '__main__.ModuleA'>}
{'a': <class '__main__.ModuleA'>, 'b0': <class '__main__.ModuleB'>, 'b1': <class '__main__.ModuleB'>, 'b2': <class '__main__.ModuleA'>}
if you want to add the class members dynamically you can use this code:
for i in range(2):
MyDesign.a = lambda: None
setattr(MyDesign.a, f"b{i}", None)
MyDesign.__annotations__[f"b{i}"] = ModuleB
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…