Rafael Sanchez
Rafael Sanchez

Reputation: 414

Dynamically set attribute on class

Can class attributes be set dynamically?

Something like this:

class MyConstants:

    GLOBAL_VAR = 'actual_attr_name'

class MyStrings:

    setattr(cls, MyConstants.GLOBAL_VAR, None)

I wish to automate setting a number of class attributes, for which I don't know/want to hardcode their names... instead fetch them from another class. The snipped above returns

NameError: name 'cls' is not defined

Upvotes: 1

Views: 266

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96257

Two ways to do this:

Use locals:

>>> class Foo:
...     locals()['dynamic_value'] = 42
...
>>> Foo.dynamic_value
42

But the above isn't really guaranteed to work.

So best is probably to use:

>>> class Foo:
...     pass
...
>>> setattr(Foo, 'dynamic_value', 42)
>>> Foo.dynamic_value
42

Upvotes: 4

Related Questions