Python __sub__() Magic Method

Syntax

object.__sub__(self, other)

Python’s object.__sub__(self, other) method returns a new object that represents the difference of two objects. It implements the subtraction operator - in Python.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Example

In the following example, you create a custom class Data and overwrite the __sub__() method so that creates a new Data object with the value being the difference a-b of the values of the two operands a and b of type Data.

class Data:

    def __init__(self, value):
        self.value = value
        
    def __sub__(self, other):
        return Data(self.value - other.value)


a = Data(44)
b = Data(2)
c = a - b

print(c.value)
# 42

You have defined the dunder method so that the resulting difference of two Data objects is a Data object itself:

print(type(c))
# <class '__main__.Data'>

If you hadn’t defined the __sub__() method, Python would’ve raised a TypeError.

How to Resolve TypeError: unsupported operand type(s) for –

Consider the following code snippet where you try to subtract two custom objects without defining the dunder method __sub__():

class Data:

    def __init__(self, value):
        self.value = value


a = Data(44)
b = Data(2)
c = a - b

Running this leads to the following error message on my computer:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 9, in <module>
    c = a - b
TypeError: unsupported operand type(s) for -: 'Data' and 'Data'

The reason for this error is that the __sub__() dunder method has never been defined—and it is not defined for a custom object by default. So, to resolve the TypeError: unsupported operand type(s) for -, you need to provide the __sub__(self) method in your class definition as shown previously:

class Data:

    def __init__(self, value):
        self.value = value
        
    def __sub__(self, other):
        return Data(self.value - other.value)

Related Video

Advanced Example – Set Difference Overwrite

To use the subtraction operator on custom objects, define the __sub__() dunder method that takes two arguments: self and other and returns the result of self - other. You can define the specific behavior by using the attributes (data) maintained in this object.

In the following code, you create a basket from {'coffee', 'banana', 'bred'} but then you remove the contents in another basket {'bred'} from it—for example to prevent double-purchasing:

class Basket:
    def __init__(self, goods):
        self.goods = goods

    def __sub__(self, other):
        return Basket(self.goods - other.goods)

my_basket = Basket({'coffee', 'banana', 'bred'})
to_remove = Basket({'bred'})

updated_basket = my_basket - to_remove
print(updated_basket.goods)

The output of this code snippet is the new basket:

{'banana', 'coffee'}

The code consists of the following steps:

  • Create the class Basket that holds the list contents to store some goods.
  • Define the magic method __sub__ that creates a new Basket by combining the sets of goods from the two operands’ baskets. Note that we rely on the already implemented subtraction operator on sets, i.e. set difference, to actually implement the subtraction operator for baskets.
  • We create two baskets my_basket and to_remove, and calculate the difference between them to a new basket updated_basket.

Python __sub__ vs __isub__

Python provides the operator x -= y to subtract two objects in-place by calculating the difference x - y and assigning the result to the first operands variable name x. You can set up the in-place subtraction behavior for your own class by overriding the magic “dunder” method __isub__(self, other) in your class definition.

>>> x = 3
>>> x -= 2
>>> x
1

The expression x -= y is syntactical sugar for the longer-form x = x - y:

>>> x = 3
>>> x = x - 2
>>> x
1

So, the difference between the __sub__ and __isub__ methods is the following:

If you overwrite the Python dunder __sub__ method, you’ll define the result of the computation a - b. If you overwrite the Python dunder __isub__ method, you’ll define the result of the computation a =- b that modifies the first operand a rather than returning a new object. In other words, the former operator is the subtraction, and the latter is the in-place subtraction operator.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!