Setting Class attributes from dictionary

Viewed 187

I have a class which inherits from Enum and str. I need to define some class attributes which are defined in a .json file and is being loaded in a Python dictionary.

from enum import Enum

# I want to create a class like this (but assign the class attributes by reading a dict)

class Test(str, Enum):
  A = 'Alpha'
  B = 'Beta'

# Attempt to solve :

mydict = { 'A' : 'Alpha', 'B' : 'Beta' }

class Test1(str, Enum):
  for k,v in mydict.items():
    k = v

# => An Error is reported here.

For class instances, I can use setattr() but I could not find anything to set the class attributes.

Since these attributes are dynamic and could change, I do not want to hard-code the class attributes but rather read in a dictionary and set it.

4 Answers

Don't define your own class directly, instead use the Enum functional API:

Test = enum.Enum("Test", mydict, type=str)

You can use setattr() too for classes:

>>> class A: 
...     pass
...
>>> setattr(A, "attribute", 3)
>>> inst = A()
>>> inst.attribute
3

Just iterate through the dict like this:

for k, v in mydict.items():
     setattr(Test, k, v)

To make this dynamic, you can set all attributes under __new__ magic function. An example of this is here:

attr_dict ={
    'A': 'alpha',
    'B': 'beta'
}

class MyClass:
    def __new__(cls, *args, **kwargs):
        for k, v in attr_dict.items():
            setattr(cls, k, v)
        return cls

x = MyClass()

x.A  # --> 'alpha'
x.B  # --> 'beta'

This answer should help you.

From answer:

Python 3

for k, v in mydict.items():
    exec("%s=%s" % (k,v))

That doesn't smell like good practice, but works.

Related