2

I would like to override an attribute with a property, but only on one instance. Here is how I try to solve it, but it does not do what I would like to:

class Foo:
    def __init__(self):
        self.bar = True
        self._hidden = False

a = Foo()
print(a.bar)
a.bar = property(lambda self: self._hidden)
print(a.bar)


>>> C:\Users\Ilya\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/Ilya/pydolons/experiment.py
>>> True
>>> <property object at 0x0323B960>

Can it be done? what is the actual mechanics of dunder calls that enable class property, but not the one which is set on the instance?

Following code does what I want to do, but it modifies the class:

class Foo:
    def __init__(self):
        self.bar = True
        self._hidden = False

a = Foo()
print(a.bar)
Foo.bar = property(lambda self: self._hidden)
print(a.bar)

>>> C:\Users\Ilya\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/Ilya/pydolons/experiment.py
>>> True
>>> False

1 Answer 1

6

Can it be done?

It can not.

A property is a descriptor, and descriptors can only be declared on the class level.

Allowing instance descriptors was proposed, but rejected.


If you are fine with migrating this instance to a different class, you could do that:

def attach_property(instance, key, prop):
    class Derived(instance.__class__):
        pass
    setattr(Derived, key, prop)
    instance.__class__ = Derived

which you could then use like this:

a = Foo()
print(a.bar)
attach_property(a, "bar", property(lambda self: self._hidden))
print(a.bar)
Sign up to request clarification or add additional context in comments.

5 Comments

can I dynamically craft a copy of the class and put it there not to affect other instances?
You can have those instances be instances of a different class, and classes can be dynamically created (e.g. as subclasses of the desired class), so.. I guess?
@ikamen I don't know if I understood what you meant, but I put a suggestion in my edit.
awesome! I believe it will even pass the isinstance() check, any drawbacks you know to this solution?
@ikamen Apart from the surprise that the instance is no longer actually the same type as other instances, and the general weirdness of the solution, not really.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.