warvariuc
warvariuc

Reputation: 59674

Getter method vs read-only property

There already was a similar question "When and how to use the builtin function property() in python", but I thing this is one is different.

I have a class that needs a method to get a counter of some work progress:

class Downloader():

    def __init__(self, max_workers):
        self.executor = ThreadPoolExecutor(max_workers)

    @property
    def unfinished_tasks_count(self):
        return self.executor._work_queue.unfinished_tasks

I think it's better to do:

class Downloader():

    ...

    def get_unfinished_tasks_count(self):
        return self.executor._work_queue.unfinished_tasks

because when it's property looking at the interface (without looking at the docs and/or source code) it is not explicit that it's a read-only, computed attribute. When it's a method it is clear that it is only a getter of a computed value and it's not a simple attribute that can be set by an API client.

So my question is: When to use a getter method vs a read-only property?

Upvotes: 3

Views: 185

Answers (1)

Helmut Grohne
Helmut Grohne

Reputation: 6788

The usage of properties should bear your intention and provide a reasonable expectation to your peers.

When not to use a property:

  • When it involves a computation that may take non-constant time. This would counter the intuition that accessing an attribute is a fast thing to do.
  • When it bears some external state, that is changed by someone else than your peer accessing the property. Doing so would counter the intuition that accessing the attribute twice yields the same result. On the other hand when you need the result of a method call twice, you usually store it in a local variable and thereby avoid it changing in between.

When to use properties:

  • Mainly when not using properties becomes a burden (syntactically).
  • When you need to implement a particular interface (duck typing) and there is no other way to do it.

As usual with such questions, answers are subject to taste and there are no hard rules. These guidelines may serve you well in many cases, but they do not remove the need to apply common sense.

Upvotes: 4

Related Questions