Skip to content
Advertisement

Define Python type hints in for-loop inside class body

I have the following code in Python:

JavaScript

The type hints are used upon instantiation of MyDesign to dynamically add instances of the various Modules. I chose this syntax because the class MyDesign is really just a “template” defining what Modules it’s composed of, but the instantiation of modules needs some arguments only available when MyDesign is being instantiated.

I would like to simplify the definition of MyDesign into something like

JavaScript

Is this possible?

Advertisement

Answer

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:

JavaScript

result of running this code:

JavaScript

if you want to add the class members dynamically you can use this code:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement