Search code examples
pythonpropertiespython-internals

How and when are python @properties evaluated


Here's a snippet of code.

class TestClass:
    def __init__(self):
        self.a = "a"
        print("calling init")

    @property
    def b(self):
        b = "b"
        print("in property")
        return b

test_obj = TestClass()
print("a = {} b = {}".format(test_obj.a,test_obj.b))

I'm trying to understand when the variable b defined inside test_obj gets its value of "b".

As you can see from the below screenshot, the statement on line 13 is yet to be evaluated/executed but already the value of b for test_obj has been initialized. Debugging this by placing a breakpoint on literally every single line didn't help me understand how this is happening.

enter image description here Can someone please explain this to me ?


Solution

  • More likely, the IDE is trying to show you what the value of test_obj.b is. For that it gets the value from test_obj.b. Since it doesn't make much of a difference whether b is an attribute or a @property, the debugger essentially just does test_obj.b for you, which gives it the value 'b'.

    The function def b works exactly as you might expect from any other ordinary function; it's just that the debugger/IDE implicitly invokes it for you.