1

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

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Rafael Sanchez
  • 394
  • 7
  • 20
  • 1
    Where are the class attribute names coming from? Is that what `MyConstants.GLOBAL_VAR` is for? What do you expect `cls` to be here (`cls` isn't a keyword or anything)? You never set that to anything? Can I assume you want to put that `setattr()` line inside of `__init__()` and use `self` instead of `cls`. – gen_Eric Mar 19 '21 at 15:18
  • `MyConstants` is coming from another package – Rafael Sanchez Mar 19 '21 at 15:24
  • 1
    I was hoping not to have to instantiate the class, as it will contain constants. Therefore the question on how to access the class from within using `setattr` – Rafael Sanchez Mar 19 '21 at 15:27
  • Oh! I see what you are trying to do now. – gen_Eric Mar 19 '21 at 15:29
  • Does this answer your question? [Dynamically create class attributes](https://stackoverflow.com/questions/2583620/dynamically-create-class-attributes) – gen_Eric Mar 19 '21 at 15:31

1 Answers1

4

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
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172