3

How '@decorator' actually works?

I just knew it works like this:

def deco(func):...

@deco
def func():...

# same
def func():...
func = deco(func)

But it doesn't work well in '@class.method'

Below is an example:

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self.value):
        self._name = value

class Person:
    def __init__(self, name):
        self._name = name

    ## @propery
    def name(self):
        return self._name
    name = property(name)

    ## @name.setter
    def name(self, value):
        self._name = value
    name = name.setter(name) <----- error 

The error here is because name has been changed to point to "def name(self.value):..."

I'd like to know how '@property.method' actually works.

I just guessed like that:

class Person:
    def __init__(self, name):
        self._name = name
    
    ## @propery
    def name(self):
        return self._name
    name = property(name)

    ## @name.setter
    x = name.setter
    def name(self, value):
        self._name = value
    name = x.setter(name)
    del x 

Is it right or is there other way to work that I don't know?

Thank you for reading!

  • Does this answer your question? [How does property decorator work internally using syntactic sugar(@) in python?](https://stackoverflow.com/questions/62952223/how-does-property-decorator-work-internally-using-syntactic-sugar-in-python) – S.B Jan 31 '22 at 07:53
  • 1
    The `@` decorator application is basically able to "intercept" the `def ...()` before it has been assigned to `name`, so the intermediate assignment to `name` and its replacement doesn't happen. – deceze Jan 31 '22 at 07:56
  • I am trying to read PEP 318 but I think it doesn't have how decorator works. Now, I am searching how `@` operator can intercept `def func():...` Thank you for your answer! – KayyoungH L Jan 31 '22 at 08:20
  • @KayyoungHL Did you check the ThierryLathuille's answer in that link ? – S.B Jan 31 '22 at 08:21
  • @soroush-bakhtiary Yes, I check that link and now I know decorator works without the intermediate assignment to the variable func. But my question is how it work like that? I mean I'd like to know how the `@` operator for decorator actually works. I guess it also works following python syntax. – KayyoungH L Jan 31 '22 at 08:27
  • I've tried a bunch of different things. But I have no idea how to translate the syntactic sugar of `@name.setter`. My guess is that it intercepts the setter method and sets it as a lambda function so that the property is not overridden. Overriding the property is what happens when trying to do it without syntactic sugar using the normal decorator rules as the question shows. – geckels1 Mar 28 '23 at 01:47

0 Answers0