Setting a class attribute with a given name in python while defining the class

prismofeverything picture prismofeverything · Mar 25, 2010 · Viewed 14.4k times · Source

I am trying to do something like this:

property = 'name'
value = Thing()
class A:
  setattr(A, property, value)
  other_thing = 'normal attribute'

  def __init__(self, etc)
    #etc..........

But I can't seem to find the reference to the class to get the setattr to work the same as just assigning a variable in the class definition. How can I do this?

Answer

Vitalik Verhovodov picture Vitalik Verhovodov · Dec 16, 2013

You can do it even simpler:

class A():
    vars()['key'] = 'value'

In contrast to the previous answer, this solution plays well with external metaclasses (for ex., Django models).