Mihai H
Mihai H

Reputation: 3291

Python - How to get the attribute behind @property

How can I get the attribute behind a property in Python? I have the following scenario:

class User(object):
    def __init__(self):
        self._email = None

    @property
    def email(self):
       return self._email

    @email.setter
    def email(self, value):
         self._email = value

What I wan to achieve is to get the _email attribute which is behind email property using reflection. Any hint is much appreciated.

Upvotes: 0

Views: 93

Answers (1)

user2357112
user2357112

Reputation: 280182

There's no general way to do this, since a property doesn't have to simply be a proxy for a private attribute. You could have any of the following:

@property
def foo(self):
    return 4

@property
def bar(self):
    return self._bar**2

@property
def baz(self):
    sys.exit(1)

@property
def spam(self):
    if self._spam is None:
        self._spam = self._lazily_compute_spam()
    return self._spam

If you wanted to try it anyway, you could try to get the source code of the property method with the inspect module and parse it, or decompile the bytecode, but both are terribly fragile ideas.

Upvotes: 2

Related Questions