beebek
beebek

Reputation: 1947

similar use of operator overloading in python functions

Is there a way to use variable like in operator overloading. e.g.

a += 1

Instead of a = a + 1

in

a = max(a, some_other_variable)

The max() function is just an example.


NOTE: My intent here is not to use the variable 'a' again, if possible. These two examples are different and not related to each other. e.g.

a = some_function(a, b)

Here, the values returned from some_function() is assigned back to variable 'a' again. Unless variable 'a' is a class variable I cannot access variable inside function some_function(), although if there is a way so that I can use it only once?

Upvotes: 0

Views: 79

Answers (3)

JBernardo
JBernardo

Reputation: 33407

Instead of overloading an operator in a like the other answer, you could create a partial-like object for the second part. (I used the left shift operator for "coolness")

class partial(functools.partial):
    def __rlshift__(self, val):
        return self(val)

and use like this:

>>> a = 10
>>> a <<= partial(max, 20)
>>> a
20

So you don't need to mess with your variable types to execute the operation. Also you will not need to declare a new class for every function.

PS: Beware that the actual execution is max(20, a).

Upvotes: 0

mgilson
mgilson

Reputation: 310089

I feel like you want something along these lines ...

>>> class Foo(object):
...     def __iadd__(self, other):
...         return max(self.num, other)
...     def __init__(self, num):
...         self.num = num
... 
>>> a = Foo(5)
>>> a += 4
>>> print a
5
>>> a = Foo(4)
>>> a += 6
>>> a
6

But please note that I would consider this use of __iadd__ to be very impolite. Having __iadd__ return something other than self is generally inconsiderate if the type is mutable.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799160

You cannot supplement Python's set of operators and statements directly in the Python code. However, you can write a wrapper that uses Python's language services to write a Pythonesque DSL which includes the operators you want.

Upvotes: 2

Related Questions