Don't use Python's property (www.b-list.org)
from jnovinger@programming.dev to python@programming.dev on 05 Jan 2024 16:34
https://programming.dev/post/8167609

#python

threaded - newest

troyunrau@lemmy.ca on 05 Jan 2024 17:05 next collapse

Tl;dr: don’t use @property during design, it’s almost certainly the wrong pattern. But use it to retrofit a method to a value.

sugar_in_your_tea@sh.itjust.works on 06 Jan 2024 05:09 collapse

Yup. I pretty much only use it if I need to ensure new values are valid or provide a default value.

I do the same in other languages, like C# and JavaScript. Properties are cool, but should be quite rare.

[deleted] on 05 Jan 2024 19:45 next collapse
.
souperk@reddthat.com on 05 Jan 2024 22:05 next collapse

this is a method, and always was a method, I just wanted it to look like an attribute for aesthetic reasons

I think “aesthetic reasons” is an oversimplification. There are certain assumptions a developer makes when reading some code that uses properties. While these assumptions are not clearly defined and may differ per developer, I think there is a common core.

(1) There are no side-effects. The object is not mutated (or any other object), no IO takes place.

(2) The time and space complexity is O(1).

(3) The result is consistent. Consequent calls to the property should return the same value unless there is a mutation between them.

VitulusAureus@lemmy.world on 05 Jan 2024 23:42 collapse

The combination of properties 1 and 3 makes it a pure function, which is also useful in compiled or jittable languages because it allows for a variety of optimizations.

synae@lemmy.sdf.org on 05 Jan 2024 17:06 collapse

Nah, I think I’ll continue to.