Oli
Oli

Reputation: 16035

Override operator of built-in object

I would like to override the "+" operator of the "dict" class, in order to be able to merge two dictionaries easily.

Something like that:

def dict:
  def __add__(self,other):
    return dict(list(self.items())+list(other.items()))

Is it possible in general to override the operator of a built-in class?

Upvotes: 3

Views: 1981

Answers (3)

JadedTuna
JadedTuna

Reputation: 1823

You can create subclass of dict (as @NPE said):

class sdict(dict):
    def __add__(self,other):
        return sdict(list(self.items())+list(other.items()))

I am not sure, but you can try to modify some objects in site.py. Doesn't work


Why not to create your own Python Shell?

Here is an example:

shell.py

#!/usr/bin/env python

import sys
import os

#Define some variables you may need

RED = "\033[31m"

STD = "\033[0m"

class sdict(dict):
    def __add__(self,other):
        return dict(list(self.items())+list(other.items()))

dict = sdict

sys.ps1 = RED + ">>> " + STD
del sdict # We don't need it here!


# OK. Now run our python shell!
print sys.version
print 'Type "help", "copyright", "credits" or "license" for more information.'
os.environ['PYTHONINSPECT'] = 'True'

Upvotes: 3

NPE
NPE

Reputation: 500227

In a word, no:

>>> dict.__add__ = lambda x, y: None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'dict'

You need to subclass dict to add the operator:

import copy

class Dict(dict):

  def __add__(self, other):
    ret = copy.copy(self)
    ret.update(other)
    return ret

d1 = Dict({1: 2, 3: 4})
d2 = Dict({3: 10, 4: 20})
print(d1 + d2)

Personally, I wouldn't bother and would just have a free function for doing that.

Upvotes: 7

Alexander Zhukov
Alexander Zhukov

Reputation: 4547

This might look like the following:

 class MyDict(dict):
     def __add__(self,other):
         return MyDict(list(self.items())+list(other.items()))

Upvotes: 1

Related Questions