homepage

This issue tracker has been migrated to GitHub , and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Add 'composable' decorator to functools (with @ matrix multiplication syntax)
Type: enhancement Stage: resolved
Components: Library (Lib) Versions: Python 3.6
process
Status: closed Resolution: later
Dependencies: Superseder:
Assigned To: Nosy List: levkivskyi, r.david.murray
Priority: normal Keywords:

Created on 2015年05月06日 10:24 by levkivskyi, last changed 2022年04月11日 14:58 by admin. This issue is now closed.

Messages (2)
msg242653 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2015年05月06日 10:24
The matrix multiplication operator @ is going to be introduced in Python 3.5 and I am thinking about the following idea:
The semantics of matrix multiplication is the composition of the corresponding linear transformations.
A linear transformation is a particular example of a more general concept - functions.
The latter are frequently composed with ("wrap") each other. For example:
plot(real(sqrt(data)))
However, it is not very readable in case of many wrapping layers. Therefore, it could be useful to employ
the matrix multiplication operator @ for indication of function composition. This could be done by such (simplified) decorator:
class composable:
 def __init__(self, func):
 self.func = func
 def __call__(self, arg):
 return self.func(arg)
 def __matmul__(self, other):
 def composition(*args, **kwargs):
 return self.func(other(*args, **kwargs))
 return composable(composition)
I think using such decorator with functions that are going to be deeply wrapped
could improve readability.
You could compare (note that only the outermost function should be decorated):
plot(sorted(sqrt(real(data_array)))) vs. (plot @ sorted @ sqrt @ real) (data_array)
I think the latter is more readable, also compare
def sunique(lst):
 return sorted(list(set(lst)))
vs.
sunique = sorted @ list @ set
Apart from readability, there are following pros of the proposed decorator:
1. Similar semantics as for matrix multiplication.
2. Same symbol for composition as for decorators.
3. The symbol @ resembles mathematical notation for function composition: ∘
I think it could be a good idea to add such a decorator to the stdlib functools module.
msg242663 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2015年05月06日 13:02
This should be taken to python-ideas (and probably pypi) first. You can reopen if there is agreement that this should be done. IMO it should not be done for 3.5 in any case.
History
Date User Action Args
2022年04月11日 14:58:16adminsetgithub: 68321
2015年05月06日 13:02:02r.david.murraysetstatus: open -> closed

versions: + Python 3.6, - Python 3.5
nosy: + r.david.murray

messages: + msg242663
resolution: later
stage: resolved
2015年05月06日 10:24:42levkivskyicreate

AltStyle によって変換されたページ (->オリジナル) /