Search code examples
pythonmonkeypatching

In Python can I change the structure of a class at runtime?


In Python you can add new instance variables to an instance of a class at runtime like this...

>> class Foo:
>>     def __init__(self, bar):
>>         self.bar = bar
>> 
>> f = Foo()
>> setattr(f, "baz", "spam")
>> f.baz
"spam"

...but it only has effect on the instance f not the class foo.

>> x = Foo()
>> x.baz
AttributeError: 'Foo' object has no attribute 'baz'

Is there a way to add the new instance variable baz to the class Foo, so that all new instances of that class have the new variable?


Solution

  • You could set the attribute of the class instead of the instance.

    setattr(Foo, "baz", "spam")
    

    Output

    >>> class Foo:
    ...     def __init__(self, bar):
    ...         self.bar = bar
    
    >>> f = Foo('bar')
    >>> setattr(Foo, "baz", "spam")
    >>> f.baz
    'spam'
    >>> f2 = Foo('bar')
    >>> f2.baz
    'spam'