(One of my summaries of the 2024 Dutch PyGrunn python&friends conference in Groningen, NL).
“Descriptors” are re-usable @property
-like items. They implement the __get__
,
__set__
and __delete__
methods and possibly the __set_name__
method.
See https://docs.python.org/3/howto/descriptor.html for an introduction on the python website.
Most of the talk consisted of code examples: I’m not that fast a typer :-) So this summary is mostly a note to myself to check it out deeper.
You can use them for custom checks on class attributes, for instance. Or for some security checks. Or for logging when an attribute is updated.
This is how it looks when you use it:
class Something:
id = PositiveInteger() # <= this is your descriptor
So usage of a descriptor is easy. The hard and tricky part is actually writing them. If you don’t really need them: don’t try to write them. If you write code that is used a lot, the extra effort might pay off.
A funny one was an Alias
descriptor:
class Something:
name: str
full_name = Alias("name")
nickname = Alias("name")
something = Something()
something.name = "pietje"
something.name # Returns pietje
something.full_name # Returns pietje, too
something.nickname # Returns pietje, too
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):