In this question I asked about a function composition operator in Python. @Philip Tzou offered the following code, which does the job.
import functools
class Co
You can't have what you want. The .
notation is not a binary operator, it is a primary, with only the value operand (the left-hand side of the .
), and an identifier. Identifiers are strings of characters, not full-blown expressions that produce references to a value.
From the Attribute references section:
An attribute reference is a primary followed by a period and a name:
attributeref ::= primary "." identifier
The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier.
So when compiling, Python parses identifier
as a string value, not as an expression (which is what you get for operands to operators). The __getattribute__
hook (and any of the other attribute access hooks) only has to deal with strings. There is no way around this; the dynamic attribute access function getattr() strictly enforces that name
must be a string:
>>> getattr(object(), 42)
Traceback (most recent call last):
File "", line 1, in
TypeError: getattr(): attribute name must be string
If you want to use syntax to compose two objects, you are limited to binary operators, so expressions that take two operands, and only those that have hooks (the boolean and
and or
operators do not have hooks because they evaluate lazily, is
and is not
do not have hooks because they operate on object identity, not object values).