Victor Stanescu
Victor Stanescu

Reputation: 461

Improve property decorator's performance?

I tried to understand and use the property decorator mainly for making the property read only. I saw that, every time the property is used, it enters the property decorator.

In my example, it enters the decorator three times, once for every print:

class PropTest:

    def __init__(self,x):
        self._x = x

    @property
    def x(self):
        return self._x

    def check(self):
        print(self.x + 1)
        print(self.x + 2)
        print(self.x + 3)

t = PropTest(3)
t.check()

If I define the property in __init__, it will enter it only once.

class PropTest:

    def __init__(self,x):
        self.x = x

    def check(self):
        print(self.x + 1)
        print(self.x + 2)
        print(self.x + 3)

t = PropTest(3)
t.check()

Am I using the decorator in a wrong way? Is there any performance issues when I am using it?

L.E. :

This is how I try to use property decorator. I don't want to read the excel each time the property is used and I want the dataframe to be read only.

@property
def rules_df(self):
    """
    :return: A dataframe that contains the rules for labels
    """
    self._rules_df = pd.read_excel(self.cfg_file)
    return self._rules_df

Upvotes: 1

Views: 354

Answers (2)

Vlad Bezden
Vlad Bezden

Reputation: 89627

There is no point to create property just to expose object attribute. You use the property if you need to add some logic there. Properties are very often used in languages like Java, C#, but in a language like Python, you can directly access attribute without creating property. Accessing an object attribute via property has a performance impact as you see in your example. Your second example is a more Pythonic way of coding.

Upvotes: 1

André C. Andersen
André C. Andersen

Reputation: 9375

You are using the property correctly in the first example. In the second example you are not using a property, but just setting a member of the object.

A property is just syntactic sugar for making a method act like a field.

There might be a slight performance hit. Usually nothing to worry about.

If you want to set the value of a property this Q/A on SO might help.

Upvotes: 1

Related Questions