Reputation: 59674
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
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 to use properties:
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