Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python catching functions

I have written the following code that works.

from operator import mul
from operator import truediv #python 3.2

class Vec(list):

    def __mul__(self, other):
        return Vec(map(mul, self, other))

    def __truediv__(self, other):
        return Vec(map(truediv, self, other))


>>> xs = Vec([1,2,3,4,5])
>>> ys = Vec([4,5,6,7,4])
>>> zs = xs * ys
>>> zs.__class__
<class 'vector.Vec'>
>>> zs
[4, 10, 18, 28, 20]

but is it possible to create something like this:

class Vec(list):

    allowed_math = [__add__, __mul__, __truediv__, __subtract__] # etc

    def __catchfunction__(self, other, function):
        if function in allowed_math:
            return Vec(map(function, self, other))

Just to make clear, This in not about me trying to re-create NumPy, I am merely trying to understand how one can play with Python.

like image 267
beoliver Avatar asked May 10 '26 02:05

beoliver


1 Answers

One option to achieve the desired effect is this:

class Vec(list):
    pass

functions = {"__add__": operator.add,
             "__mul__": operator.mul,
             "__truediv__": operator.truediv,
             "__sub__": operator.sub}
for name, op in functions.iteritems():
    setattr(Vec, name, lambda self, other, op=op: Vec(map(op, self, other)))

Note that the op=op parameter is necessary to avoid the lambda function becoming a closure over op.

You might be much better off using NumPy though – it offers a much more versatile and efficient numerical array implementation than you would be able to create yourself in pure Python.

like image 118
Sven Marnach Avatar answered May 12 '26 10:05

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!