Python: How to overload operator with ast

operator overloading in python example
python operator overloading assignment
method overloading in python 3
python ast
python ast to code
function overloading and overriding in python
python overload decorator
python operator overloading different types

My problem is to redefine +-operator evaluating expression with ast. I have a list of expressions and it simple to resolve with eval():

>>> expr = '1+2*3**4/5'
>>> print(eval(expr))
33.4

But I like to redefine the +-operator (addition) for list and dict like this:

expr = '[1,2,3]+[4,5,6]'

regular result with eval is

[1, 2, 3, 4, 5, 6]

but I'd like to have

[5, 7, 9]

like it is in R-language.

The same should work also for dictionaries like this:

expr = "{'a':1, 'b':2} + {'a':3, 'b':4}"

I'd like to have

{'a': 4, 'b': 6}

In short words, I think to replace ordinary add function, that when operands are list or dict correct actions.

I tried to use ast and NodeTransformer but without success. Someone can help me?


Operator Overloading in Python, datatype, so the code won't be executed if it's not. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.


Make your own list class and define the addition operator on it:

class MyKindOfList(list):
    def __add__(self, other):
        return MyKindOfList(a + b for a, b in zip(self, other))

Then you can do this:

x = MyKindOfList([1, 2, 3])
y = MyKindOfList([4, 5, 6])

print (x + y)  # prints [5, 7, 9]

Python Questions and Answers – Operator Overloading, How to overload built-in functions and operators in your custom Python classes in The str() built-in is used to cast an instance of a class to a str object, or more  Now we know how function overloading works, the next section focusses on operator overloading. Operator Overloading. Python allows us to change the default behavior of an operator depending on the operands that we use. This practice is referred to as "operator overloading". The functionality of Python operators depends on built-in classes.


starting from suggestion of Aran-Fey and reading something from this link I wrote a more readable code to resolve the problem

import ast
from itertools import zip_longest

def __custom_add(lhs, rhs):
    if isinstance(lhs,list) and isinstance(rhs, list):
        return [__custom_add(l, r) for l, r in zip_longest(lhs, rhs, fillvalue=0)]

    if isinstance(lhs, dict) and isinstance(rhs, dict):
        keys = lhs.keys() | rhs.keys()
        return {key: __custom_add(lhs.get(key,0), rhs.get(key,0)) for key in keys}

    return lhs + rhs

class SumTransformer(ast.NodeTransformer):

    def visit_BinOp(self, node):
        if isinstance(node.op, ast.Add):
            new_node = ast.Call(func=ast.Name(id='__custom_add', ctx=ast.Load()),
                            args=[node.left, node.right],
                            keywords = [],
                            starargs = None, kwargs= None
                            )
            ast.copy_location(new_node, node)
            ast.fix_missing_locations(new_node)
            return new_node

        return node

expr = [
    '(2 + 3 * 4)/2',
    '[1, 2] + [3, 4]',
    "{'a': 1} + {'a': -2}"
    ]


for e in expr:
    syntax_tree = ast.parse(e, mode='eval')
    syntax_tree = SumTransformer().visit(syntax_tree)
    res = eval(compile(syntax_tree, '<ast>', 'eval'))
    print(res)

# results

# 7.0
# [4, 6]
# {'a': -1}

Thanks to all people helped me

Using python's eval() vs. ast.literal_eval()?, How to overload the operators in Python? Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have  Overloading, in the context of programming, refers to the ability of a function or an operator to behave in different ways depending on the parameters that are passed to the function, or the operands that the operator acts on [1]. In Python, operator overloading (also known as “operator ad-hoc polymorphism”) in particular is a form of


ast — Abstract Syntax Trees, What is operator overloading in Python? Python operators p1 = Point(2,3) >>> p2 = Point(-1,2) >>> p1 + p2 Traceback (most recent call last): TypeError:  1. Python Operator Overloading. In this Python tutorial, we are going to discuss Python Operator Overloading, examples of operator overloading in python, and python magic methods with some operators: python binary operator, python comparison operator, python unary operators, and python extended assignments.


Operator and Function Overloading in Custom Python Classes , Traceback (most recent call last): File "C:/Users/admin/func.py", line 8, To see Python's operator overloading in action, launch the Python terminal and run the  Overloading the + Operator in Python. To overload the + sign, we will need to implement __add__() function in the class. With great power comes great responsibility. We can do whatever we like, inside this function. But it is sensible to return a Point object of the coordinate sum.


Python Operator Overloading, By studying operator overloading, we will better understand how Python executes our In light of the last lecture, I should have named this self/instance variable  For the Love of Physics - Walter Lewin - May 16, 2011 - Duration: 1:01:26. Lectures by Walter Lewin. They will make you ♥ Physics. Recommended for you