Dynamically adding @property in python

The property descriptor objects needs to live in the class, not in the instance, to have the effect you desire. If you don’t want to alter the existing class in order to avoid altering the behavior of other instances, you’ll need to make a “per-instance class”, e.g.:

def addprop(inst, name, method):
  cls = type(inst)
  if not hasattr(cls, '__perinstance'):
    cls = type(cls.__name__, (cls,), {})
    cls.__perinstance = True
    inst.__class__ = cls
  setattr(cls, name, property(method))

I’m marking these special “per-instance” classes with an attribute to avoid needlessly making multiple ones if you’re doing several addprop calls on the same instance.

Note that, like for other uses of property, you need the class in play to be new-style (typically obtained by inheriting directly or indirectly from object), not the ancient legacy style (dropped in Python 3) that’s assigned by default to a class without bases.

Leave a Comment