I have a few objects in my program that have about 10-15 attributes each. These attributes are set at various places in the code in various stages in the program. As it is absolutely fine to set them on the objects without having them defined in the class in Python, there’s no good authoritative list in my program of which attributes are used.
I’d like something like the following:
class MyObject(object):
attr1
attr2
I’ve looked at the property() built-in, but it’s at least 6 lines of code per property. Is there an easy way to define a list of default attributes without initializing them in Python?
UPDATE: I forgot to mention, most of the values don’t have sensible defaults and would effectively be equal to None before used.
I think Hugh Bothwell is on the right track, but it can be done more concisely:
Output:
I made
_defaultsand_default_valueclass attributes (which could be changed at runtime). (Providing a mutable default value would likely require additional code to prevent it from being shared by every instance created, however.)This would be easy to extend to allow defining different (immutable) default values for each default attribute:
Output: