3 ms·
Python's descriptor protocol is very elegant. Given: class C: def __init__(self): self.a = 1 def b(self): print(f'b
by pansa2 6y ago
Python's descriptor protocol is very elegant. Given:
class C:
def __init__(self):
self.a = 1
def b(self):
print(f'b({self})')
@property
def c(self):
print(f'c({self})')
o = C()
The descriptor protocol is a generic way to enable `o.a` to access an attribute of `o`, `o.b` to access an attribute of `C` and bind `self` to `o`, and `o.c` to access an attribute of `C`, bind `self` to `o`, and call it.
Do any other dynamic languages use a similar protocol for attribute access?
Ruby, for example, doesn't need to - it can use a simpler approach because `o.x` never refers to an attribute of `o`.
JavaScript's solution is less elegant - the way it sets the value of `this` is infamous, and AFAIK properties are treated as a special case rather than built on top of a generic protocol.
- lifthrasiir 6y agoI don't think Python's approach is particularly more elegant than JavaScript, as they both distinguish property-as-value and property-as-function. It's just a matter of where to put property-as-function (and unlike Python, JavaScript can have non-configurable properties which can be optimized). As property-as-function can subsume property-as-value, no built-in property-as-value would be truly elegant (Ruby is close, but not exact).
- sillysaurusx 6y agoI agree. Python's descriptor pattern was an endless source of confusion for me. But, it's much easier to do mixins in Python than in JS, even if the mro algorithm is a bit complicated...
- pansa2 6y agoSorry, could you clarify what you mean by “distinguish property-as-value and property-as-function“? How does Python distinguish between these two?
- lifthrasiir 6y agoThe very descriptor protocol exists to distinguish property-as-function (descriptor) from property-as-value (slot).