7

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 Composable:

    def __init__(self, func):
        self.func = func
        functools.update_wrapper(self, func)

    def __matmul__(self, other):
        return lambda *args, **kw: self.func(other.func(*args, **kw))

    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

I added the following functions.

def __mul__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))

def __gt__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))

With these additions, one can use @, *, and > as operators to compose functions. For, example, one can write print((add1 @ add2)(5), (add1 * add2)(5), (add1 > add2)(5)) and get # 8 8 8. (PyCharm complains that a boolean isn't callable for (add1 > add2)(5). But it still ran.)

All along, though, I wanted to use . as a function composition operator. So I added

def __getattribute__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))

(Note that this fouls up update_wrapper, which can be removed for the sake of this question.)

When I run print((add1 . add2)(5)) I get this error at runtime: AttributeError: 'str' object has no attribute 'func'. It turns out (apparently) that arguments to __getattribute__ are converted to strings before being passed to __getattribute__.

Is there a way around that conversion? Or am I misdiagnosing the problem, and some other approach will work?

RussAbbott
  • 2,660
  • 4
  • 24
  • 37
  • 2
    `other` in `__getattribute__` is the **name** of the attribute, it's not a binary operator like `>` or `@`. – jonrsharpe Jan 12 '19 at 17:45
  • As you saw, `.` is reserved for accessing attributes and methods. But you may use `°` which is more similar to the original operator, and will not create this problem. – FrenchMasterSword Jan 12 '19 at 17:45
  • 1
    @FrenchMasterSword what is the magic method to implement that?! It's not a valid Python operator. – jonrsharpe Jan 12 '19 at 17:46
  • Well it isn't a python operator ^^' – FrenchMasterSword Jan 12 '19 at 17:47
  • 2
    @FrenchMasterSword so... how exactly is that a useful suggestion? Are you suggesting the OP writes their own version of the interpreter to handle that symbol as an operator? – jonrsharpe Jan 12 '19 at 17:48
  • You probably want `__getattr__`, not `__getattribute__`. The former is called only when the attribute doesn't otherwise exist, the latter is called for **all** attributes. – Martijn Pieters Jan 12 '19 at 17:50
  • @MartijnPieters they'll still get the string `'add2'` not the `Composable` object, though. – jonrsharpe Jan 12 '19 at 17:52
  • @jonrsharpe: yes, good point. `__getattr__` can only deal with attribute **names**. – Martijn Pieters Jan 12 '19 at 17:53
  • Related: [How to multiply functions in python?](https://stackoverflow.com/q/30195045/674039) – wim Jan 12 '19 at 18:00
  • There is a very simple solution to your problem; drop the requirement that the operator should not be `*` or `@` and use one of those. IMHO these are much less confusing than if you'd actually succeed in using `.`. – Feuermurmel Jun 22 '21 at 09:16

3 Answers3

5

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 "<stdin>", line 1, in <module>
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).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I keep trying to find a way around this limitation, but I guess I'll have to give up. `@` and `*` are not that bad. – RussAbbott Jan 12 '19 at 19:15
  • I asked a related question here: https://stackoverflow.com/questions/54164382/more-on-function-composition-and-decorators-in-python – RussAbbott Jan 12 '19 at 22:21
  • 1
    It might also be worth noting here that, because the right-hand side of `.` must be an identifier, there is no way to override `.` such that `f . (g . h)` will work (or parse at all!), even with the `globals()` hack suggested in another answer. – djpohly Jun 15 '22 at 17:36
4

I am actually unwilling to provide this answer. But you should know in certain circumstance you can use a dot "." notation even it is a primary. This solution only works for functions that can be access from globals():

import functools

class Composable:

    def __init__(self, func):
        self.func = func
        functools.update_wrapper(self, func)

    def __getattr__(self, othername):
        other = globals()[othername]
        return lambda *args, **kw: self.func(other.func(*args, **kw))

    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

To test:

@Composable
def add1(x):
    return x + 1

@Composable
def add2(x):
    return x + 2

print((add1.add2)(5))
# 8
Philip Tzou
  • 5,926
  • 2
  • 18
  • 27
  • 1
    Very weird. But thank you very much for going to the trouble of providing this information. – RussAbbott Jan 15 '19 at 01:02
  • 1
    This only works for globals **in the module `Composable` is defined in**. And while you could then start pulling out names from the stack, this still won’t give you full expression access; those would simply be syntax errors or parsed in the wrong order. – Martijn Pieters Jan 15 '19 at 08:33
  • @RussAbbott not sure why you think this weird? You have a string, and `globals()` is a dictionary of the module namespace mapping strings to objects. So yes, if you limit yourself to globals in the same module you can map attribute names to globals this way. That’s an indirect path, just don’t expect to have the same expressive freedom as you have with the hooks for binary operators. – Martijn Pieters Jan 15 '19 at 08:35
  • @Martijn Pieters. You're right. "Weird" is the wrong word. What I was reacting to was that this solution works in only limited situations -- as you also point out. – RussAbbott Jan 17 '19 at 00:07
2

You can step around the limitation of defining composable functions exclusively in the global scope by using the inspect module. Note that this is about as far from Pythonic as you can get, and that using inspect will make your code that much harder to trace and debug. The idea is to use inspect.stack() to get the namespace from the calling context, and lookup the variable name there.

import functools
import inspect

class Composable:

    def __init__(self, func):
        self._func = func
        functools.update_wrapper(self, func)

    def __getattr__(self, othername):
        stack = inspect.stack()[1][0]
        other = stack.f_locals[othername]
        return Composable(lambda *args, **kw: self._func(other._func(*args, **kw)))

    def __call__(self, *args, **kw):
        return self._func(*args, **kw)

Note that I changed func to _func to half-prevent collisions should you compose with a function actually named func. Additionally, I wrap your lambda in a Composable(...), so that it itself may be composed.

Demonstration that it works outside of the global scope:

def main():
    @Composable
    def add1(x):
        return x + 1

    @Composable
    def add2(x):
        return x + 2

    print((add1.add2)(5))

main()
# 8

This gives you the implicit benefit of being able to pass functions as arguments, without worrying about resolving the variable name to the actual function's name in the global scope. Example:

@Composable
def inc(x):
    return x + 1

def repeat(func, count):
    result = func
    for i in range(count-1):
        result = result.func
    return result
    
print(repeat(inc, 6)(5))
# 11
Dillon Davis
  • 6,679
  • 2
  • 15
  • 37