1

I have a class that can be simplified to something like:

class Foo(object):
    @property
    def x(self):
        return 'Boo'

foo = Foo()
foo.x --> 'Boo'

I'm doing some testing/simulation where I want to change the x accessor property to return a different constant value, just for the foo instance. Obviously, I can't just use foo.x = '13 Candles' because it's a property! I tried:

foo.__dict__['x'] = '13 Candles'

But foo.x still returns 'Boo' after that?!

I also tried

setattr(foo, 'x', '13 Candles')

Hoping that "bypassed" the accessor machinery. But no such luck. Just an error that it's a read only property.

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • If you've defined a property, you'll need to define a setter too. – cs95 Oct 26 '17 at 00:40
  • 2
    Possible duplicate of [Overriding properties in python](https://stackoverflow.com/questions/7019643/overriding-properties-in-python) – Loïc Oct 26 '17 at 00:43
  • Do you have control of this class? – juanpa.arrivillaga Oct 26 '17 at 00:56
  • @Loïc that's a pretty old question. The original question references keywords that predated Python2.3. – Travis Griggs Oct 26 '17 at 01:01
  • Or to put it another way, I checked it out fervently hoping it would be the answer I was looking for, and wasn't any closer to seeing the solution, other then thinking, this stuff (decorators) sure has evolved a bunch over the years. – Travis Griggs Oct 26 '17 at 01:02
  • @juanpa.arrivillaga can you clarify? I wrote the Foo class, yes. I don't want to rewrite it to support this case necessarily, it's being used in production as is already. – Travis Griggs Oct 26 '17 at 01:03
  • 2
    It is not a duplicate question of the question above, because it is related to an instance, without changing the class. I would recommend the [unittest.mock](https://docs.python.org/3/library/unittest.mock.html) standard library. If you google python+mock+property you will see that it is a duplicate of many questions and that the mock docs is a solution. – hynekcer Oct 26 '17 at 01:38
  • 4
    Possible duplicate of [How to mock a readonly property with mock?](https://stackoverflow.com/questions/11836436/how-to-mock-a-readonly-property-with-mock) – hynekcer Oct 26 '17 at 01:39

0 Answers0