Home » Python OOP » Python Operator Overloading

Python Operator Overloading

Summary : in this tutorial, you’ll learn Python operator overloading and how to use it to make your objects work with built-in operators.

Introduction to the Python operator overloading

Suppose you have a 2D point class with x and y coordinate attributes :

To add two Point2D objects, you can define an add() method as follows:

The add() method raises an error if the point is not an instance of the Point2D class. Otherwise, it returns a new Point2D object whose x and y coordinates are the sums of x and y coordinates of two points.

The following creates two instances of the Point2D class and use the add() method to add two points:

This code works perfectly fine. But Python has a better way to implement it. Instead of using the add() method, you can use the built-in operator (+) like this:

When you use the + operator on the Point2D object, Python will call the special method __add__() on the object. The following calls are equivalent:

The __add__() method must return a new instance of the Point2D object.

The ability to use the built-in operator ( + ) on a custom type is known as operator overloading.

The following shows the Point2D class that implements the __add__() special operator to support the + operator:

Special methods for operator overloading

The following shows the operators with their corresponding special methods:

For example, you can implement the __sub__() method in the Point2D to support subtraction ( - ) of two points:

Overloading inplace opeators

Some operators have the inplace version. For example, the inplace version of + is +=.

For the immutable type like a tuple , a string, a number, the inplace operators perform calculations and don’t assign the result back to the input object.

For the mutable type, the inplace operator performs the updates on the original objects directly. The assignment is not necessary.

Python also provides you with a list of special methods that allows you to overload the inplace operator:

Let’s take an example of overloading the += operator.

Suppose you have a cart object and you want to add an item to the cart. To do you, you can define an add() method to the Cart class and use it like this:

Alternatively, you can implement the += operator in the Cart class. It allows you to add an item to the cart as follows:

To support the += operator, you need to implement the __iadd__ special method in the Cart class.

First, define the Item class that has three attributes name, quantity, and price. Also, it has an amount property that returns the subtotal of the item:

Second, define the Cart class that implements the __iadd__ method:

In the __iadd__ method, we raise a ValueError if the item is not an instance of the Item class. Otherwise, we add the item to the items list attribute.

The total property returns the sum of all items.

The __str__ method returns the string 'The cart is empty' if the cart has no item. Otherwise, it returns a string that contains all items separated by a newline.

Third, use the += operator to add an item to the cart:

  • Opeartor overloading allows a class to use built-in operators.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Getting Started
  • Keywords and Identifier
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python I/O and Import

Python Operators

  • Python Namespace

Python Flow Control

  • Python if...else
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python Pass

Python Functions

  • Python Function
  • Function Argument
  • Python Recursion
  • Anonymous Function
  • Global, Local and Nonlocal
  • Python Global Keyword
  • Python Modules
  • Python Package

Python Datatypes

  • Python Numbers
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary

Python Files

  • Python File Operation
  • Python Directory
  • Python Exception
  • Exception Handling
  • User-defined Exception

Python Object & Class

  • Classes & Objects
  • Python Inheritance
  • Multiple Inheritance
  • Operator Overloading

Python Advanced Topics

  • Python Iterator
  • Python Generator
  • Python Closure
  • Python Decorators
  • Python Property
  • Python RegEx
  • Python Examples

Python Date and time

  • Python datetime Module
  • Python datetime.strftime()
  • Python datetime.strptime()
  • Current date & time
  • Get current time
  • Timestamp to datetime
  • Python time Module
  • Python time.sleep()

Python Tutorials

Precedence and Associativity of Operators in Python

Python dir()

Python Lists Vs Tuples

  • Polymorphism in Python
  • Python object()

Python Operator Overloading

In Python, we can change the way operators work for user-defined types.

For example, the + operator will perform arithmetic addition on two numbers, merge two lists , or concatenate two strings .

This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading .

  • Python Special Functions

Class functions that begin with double underscore __ are called special functions in Python.

The special functions are defined by the Python interpreter and used to implement certain features or behaviors.

They are called "double underscore" functions because they have a double underscore prefix and suffix, such as __init__() or __add__() .

Here are some of the special functions available in Python,

Example: + Operator Overloading in Python

To overload the + operator, 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 more sensible to return the Point object of the coordinate sum.

Let's see an example,

In the above example, what actually happens is that, when we use p1 + p2 , Python calls p1.__add__(p2) which in turn is Point.__add__(p1,p2) . After this, the addition operation is carried out the way we specified.

Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below.

  • Overloading Comparison Operators

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Here's an example of how we can overload the < operator to compare two objects the Person class based on their age :

Here, __lt__() overloads the < operator to compare the age attribute of two objects.

The __lt__() method returns,

  • True - if the first object's age is less than the second object's age
  • False - if the first object's age is greater than the second object's age

Similarly, the special functions that we need to implement, to overload other comparison operators are tabulated below.

  • Advantages of Operator Overloading

Here are some advantages of operator overloading,

  • Improves code readability by allowing the use of familiar operators.
  • Ensures that objects of a class behave consistently with built-in types and other user-defined types.
  • Makes it simpler to write code, especially for complex data types.
  • Allows for code reuse by implementing one operator method and using it for other operators.
  • Python Classes and Objects
  • self in Python, Demystified

Table of Contents

  • Introduction
  • Example: + Operator Overloading

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

  • Python - Home
  • Python - Introduction
  • Python - Syntax
  • Python - Comments
  • Python - Variables
  • Python - Data Types
  • Python - Numbers
  • Python - Type Casting
  • Python - Operators
  • Python - Booleans
  • Python - Strings
  • Python - Lists
  • Python - Tuples
  • Python - Sets
  • Python - Dictionary
  • Python - If Else
  • Python - While Loop
  • Python - For Loop
  • Python - Continue Statement
  • Python - Break Statement
  • Python - Functions
  • Python - Lambda Function
  • Python - Scope of Variables
  • Python - Modules
  • Python - Date & Time
  • Python - Iterators
  • Python - JSON
  • Python - File Handling
  • Python - Try Except
  • Python - Arrays
  • Python - Classes/Objects
  • Python - Inheritance
  • Python - Decorators
  • Python - RegEx
  • Python - Operator Overloading
  • Python - Built-in Functions
  • Python - Keywords
  • Python - String Methods
  • Python - File Handling Methods
  • Python - List Methods
  • Python - Tuple Methods
  • Python - Set Methods
  • Python - Dictionary Methods
  • Python - Math Module
  • Python - cMath Module
  • Python - Data Structures
  • Python - Examples
  • Python - Q&A
  • Python - Interview Questions
  • Python - NumPy
  • Python - Pandas
  • Python - Matplotlib
  • Python - SciPy
  • Python - Seaborn

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Python - Assignment Operator Overloading

Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python.

Example: overloading assignment operator

In the example below, assignment operator (+=) is overloaded. When it is applied with a vector object, it increases x and y components of the vector by specified number. for example - (10, 15) += 5 will produce (10+5, 15+5) = (15, 20).

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

Operator Overloading in Python

Operator Overloading is the phenomenon of giving alternate/different meaning to an action performed by an operator beyond their predefined operational function. Operator overloading is also called  Operator Ad-hoc Polymorphism .

Python operators work for built-in classes. But the same operator expresses differently with different types. For example, The + operator will perform arithmetic addition on two numbers, merge two lists and concatenate two strings. Python allows the same operator to have different meanings according to the referring context.

Example: Depicting different use of basic arithmetic operators

How to overload an operator in python.

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.

Special Functions in Python

Global functions that begin with double underscore __ are called special functions in Python. It’s because they are not ordinary. The __init__() function which we usually define and resemble as a constructor is one of them. It gets called every time we create a new object of that class.

Magic Methods for Binary Operators in Python

Magic methods for comparison operators in python, magic methods for assignment operators in python, magic methods for unary operators, example: overloading binary + operator in python.

When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. Hence by changing the magic method’s code, we can give alternative meaning to the + operator.

Example: Overloading comparison operators in Python

Example: sample operator overloading program.

  • Python Operator Overloading
  • Python Comparison Operators
  • C programming

Python Introduction +

  • Python Introduction
  • Python History
  • Keywords And Data Types
  • Python Operators

Python Flow Control +

  • If Else Statement
  • Break And Continue

Python Functions +

  • Function Arguments
  • Recursive Functions
  • Python Modules
  • Python Packages

Python Native Data Types +

  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Strings
  • Python Sets
  • Python Dictionary

Python OOP +

  • Python Object And Class
  • Inheritance
  • Multiple Inheritance
  • Operator Overloading

File Handling +

  • Directory Management
  • Exception Handling

Advanced Topics +

  • Python Iterators
  • Python Generators
  • Python Closures
  • Python Decorators
  • Python @Property

Python Operator Overloading And Magic Methods

In this article, you will learn about Python operator overloading in which depending on the operands we can change the meaning of the operator. You will also learn about the magic methods or special functions in Python.

Operator Overloading In Python

Basically, operator overloading means giving extended meaning beyond their predefined operational meaning.

For example, a + operator is used to add the numeric values as well as to concatenate the strings. That’s because + is overloaded for int class and str class. But we can give extra meaning to this + operator and use it with our own defined class. This method of giving extra meaning to the operators is called operator overloading.

How to overload the operators in Python?

There is an underlying mechanism related to operators in Python .

The thing is when we use operators, a special function or magic function is automatically invoked that 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. So by changing this magic method’s code, we can give extra meaning to the + operator.

Just like __add__ is automatically invoked while using + operator, there are many such special methods for each operator in Python.

Overloading + operator in Python

As you can see in above example, we have overloaded + operator to add two objects by defining __add__ magic method and when we run the program it will generate following output.

That didn’t go as we expected. So, what we can do is to modify another magic method __str__ to produce the result as we desire.

Here is how we do it.

Now this will generate following output.

Python Magic Methods Or Special Functions

As we already there are tons of Special functions or magic methods in Python associated with each operator. Here is the tabular list of Python magic methods.

List of Assignment operators and associated magic methods.

List of Comparison operators and associated magic methods.

List of Binary operators and associated magic methods.

List of Unary operators and associated magic methods.

Example: Overloading extended assignment operator (+=) in Python

Example: overloading comparison(>) operator in python.

CodersLegacy

Operator Overloading in Python

Operator Overloading is a handy feature in Python that allows us to “overload” or “over-ride” an operator with our own custom code. Operators such as + , - , * , / may not work in certain situations, such as when adding together two objects from custom classes you may have created.

In order to resolve this, we “overload” these operators to ensure it correctly adds the objects in a way that we find acceptable.

Regular Data Types

You must have already used various operators with the regular data types like int and string, like the example below.

These Data types have defined behavior for these various operations. The Custom Classes that we make however, do not have defined behavior (by default). We need to code in the behavior for each operator into the Classes that we make, in order for it work correctly.

In the below example, we will demonstrate what happens if you try to use the + operator on two objects of Class Data.

The above code produces the following error:

This error was thrown since there is no support for the addition between two Data objects.

Operator Overloading

The operators that we use so often, +, *, -, / and others have special methods associated with them that we need to write. The + operator for instance, has the __add__() function which gets called when the + operator is used. You can envision the function call as object1.__add__(object2) .

The following snipped overloads the __add__() function allowing for the addition of two data objects.

The + operator now works, because there is an appropriate __add__() method, which doesn’t try adding the objects, rather it adds the variables inside the object. You can add more than just one variable too. If your object has several, you can add them all together in the overloaded method.

Also note, that the reason we return a Data object from __add__() was because we were assigning it to a Data object. Otherwise d3 would have ended up as an int , not a Data object.

To output the new value in d3 , we can always do print(d3.value) , but what if we just overloaded the print operator itself? That way we could just do print(d3) , and we could print out the value(s) we want to display.

In order to overload print() , we need to overload the __str__() method in our Data class.

The __str__() must return a string, hence we have to convert self.value to string before returning. In the case of any other data type, an error will be thrown.

In this manner, you can overload almost any operator in Python. We have a complete list of overloadable operators in the tables below.

List of Overloadable Operators in Python

Besides the below operators, there are a few other functions and built-in methods that you can overload, such as __len__() .

Assignment based operators: (Note that the assignment operator itself, = , is not overloadable.

This marks the end of the Python Operator Overloading Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

guest

Learn Operator Overloading in Python

Avatar

Kenneth Love writes on October 27, 2014

Operator Overloading in Python

Python is an interesting language. It’s meant to be very explicit and easy to work with. But what happens when how you want or need to work with Python isn’t just what the native types expose? Well, you can build classes and give those classes attributes or methods that let you use them, but then you end up having to call methods instead of being able to just add items together where it makes sense.

But what if you could just add them together? What if your Area class instances could just be added together to make a larger area? Well, thankfully, you can. This practice is called Operator Overloading because you’re overloading, or overwriting, how operators work. By “operator”, I mean symbols like + , - , and * .

Remember back in Object-Oriented Python when we overloaded __init__() to change how our classes initialized themselves? And we overrode __str__() to change how our class instances became strings? Well, we’re going to do the same thing in this article with __add__ and some friends. This controls how instances add themselves together and with others. OK, let’s get started.

Many of us here at Treehouse like to read and I think it would be neat to have a way to measure the books we’ve read. Let’s ignore the fact that several services already exist to do this very thing. I want to do it locally and in Python. Obviously I should start with a Book class.

Nothing here that we didn’t cover in Object-Oriented Python . We make an instance and set some attributes based on the passed-in values. We also gave our class a __str__ method so it’ll give us the title when we turn it into a string.

What I want to be able to do, though, is something like:

And get back 1152 (also, I had no idea I read so many books with similar page numbers). Currently, that’s not going to work. Python is going to give me an error about "TypeError: unsupported operand type(s) for +: 'int' and 'Book'" . That’s because our Book class has no idea what to do with a plus sign. Let’s fix that.

Check out:  Should I learn HTML Before Python?

Reverse Adding

So the sum() function in Python is pretty swell. It takes a list of numbers and adds them all together. So if you have a bunch of, say, baseball inning scores, you can add them together in one method without having to have a counter variable or anything like that.

But , sum() does something you probably don’t expect. It starts with 0 and then adds the first itme in the list to that. So if the first item doesn’t know how to add itself to 0, Python fails. But before it fails, Python tries to do a reversed add with the operators.

Basically, remember how 2 + 5 and 5 + 2 are the same thing due to the commutative property of addition? Python takes advantage of that and swaps the operators. So instead of 0 + Book , it tries Book + 0 . 0 + Book won’t work because the int class has no idea how to add itself to books. Our Book class can’t do the reverse add yet but we can give it the ability to.

This method has the best name in the 1990s. We have to override __radd__ , or “reverse add”.

OK, let’s try it.

But what if we want to add two Book instances together directly? If we do:

from our above example, we get another TypeError about + being unsupported for the Book type. Well, yeah, we told Python how to add them in reverse, but no matter how Python tries to put these together, one of them has to be in front, so __radd__ isn’t being used.

Related Reading:  Python for Beginners: Let’s play a/an [adjective] game

Time for regular adding, then. As you might have guessed, we override the __add__ method.

And now we can add books together:

Well, adding Book instances together seems to be pretty well sewn up. But what if we want to compare books to each other? Let’s override a few more methods so we can use < , > , and friends.

Comparative Literature

There’s a handful of methods we have to override to implement the comparison operators in our class. Let’s just do them all at once.

This works fine for < , > , == , and != , but blows up on <= and >= because we haven’t said what to compare against on other in those examples. We’ll update those two to automatically compare against .pages but we should also make them so they make sure it’s a valid comparison.

Yes, this is more work but it makes our code smarter. If we’re comparing two Book instances, we’ll use their pages attributes. If not, but we’re comparing against a number, we’ll compare that like normal. Then, finally, we’ll return a NotImplemented error for anything else. Let’s try it out.

Great! Now we can add books together to get total page counts and we can compare books to each other.

Learn more Python tools: Python One Line For Loops [Tutorial]

That’s just the beginning

If we wanted to, there are several more methods that it would make sense to override on our classes. We might want to make our Book class give back the page count when it’s turned into an int . We’d do this with the __int__ method. Or maybe we want to be able to increase or decrease page counts with += and -= . We’d do that by overriding __iadd__ and __isub__ . To see the entire list of magic methods that can be overridden, check the Python documentation . I’ve also posted the code from this article. See you next time!

Check out my Python courses at Treehouse, and try out the Treehouse 7-day free trial .

Photo from Loughborough University Library .

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

  • object-oriented

7 Responses to “Operator Overloading in Python”

Can you explain why >= and <= don't work? You wrote, "Because we haven’t said what to compare against on other in those examples," but you didn't do that with , !=, or == and yet they work without explicitly comparing self.pages to other.pages.

yeah, this thing is riddled with mistakes. dude you need a proofreader.

Under the section “Adding”, the definition of__add__ should be

def __add__(self, other): return self.pages + other.pages

yeah i noticed that too and was confused for a while and figured it must’ve been a typo. your comment confirmed it to me. these tutorials need to be very carefully proofread because any mistake can make it very confusing for a novice.

Great tutorial! Just wondering, why is it different for `=`? Why you need to do type inspection for them but not for others (“ etc)?

Hello, Python starter here!

Just wondering, does one have to overload both the add and reverse add methods to fully integrate adding functionality?

Hey Thomas,

You don’t *have* to overload both but most of the time you’ll want to. __radd__ lets Python know how to add things when the second type doesn’t match its expectations and this happens more often than you think. The good thing is, most of the time, __add__ and __radd__ are very similar, often just inverses of each other!

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

woman working on her laptop

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

Related Articles

  • Solve Coding Problems
  • Concatenate two strings using Operator Overloading in Python
  • Understanding Boolean Logic in Python 3
  • Python Bitwise Operators
  • Python 3 - Logical Operators
  • Python - Star or Asterisk operator ( * )
  • How To Do Math in Python 3 with Operators?
  • Difference between "__eq__" VS "is" VS "==" in Python
  • Logical Operators in Python with Examples
  • Modulo operator (%) in Python
  • Relational Operators in Python
  • Python Arithmetic Operators
  • Precedence and Associativity of Operators in Python
  • Operator Overloading in Python
  • A += B Assignment Riddle in Python
  • Python | Operator.countOf
  • Python Operators
  • Python Object Comparison : "is" vs "=="
  • New '=' Operator in Python3.8 f-string
  • Python | a += b is not always a = a + b

Assignment Operators in Python

Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, bitwise computations. The value the operator operates on is known as Operand .

Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables. 

Now Let’s see each Assignment Operator one by one.

1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand.

2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand.

Syntax: 

3) Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to the left operand.

Example –

 4) Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to the left operand.

 5) Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the left operand.

 6) Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the result to the left operand.

7) Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the result(floor) to the left operand.

 8) Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the left operand.

10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands and then assigning result to the left operand.

11) Bitwise XOR and Assign:  This operator is used to perform Bitwise XOR on the operands and then assigning result to the left operand.

12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on the operands and then assigning result to the left operand.

 13) Bitwise Left Shift and Assign:  This operator is used to perform Bitwise left shift on the operands and then assigning result to the left operand.

Please Login to comment...

author

  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Shorthand dict literal initialization

PEP-736 proposes a syntactic shorthand for forwarding variables to functions that accept kwargs.

I am much in favor of PEP-736. I think it addresses a very common coding pattern in a way that saves keystrokes, screen real-estate, and visual bandwidth. I also think the resulting code might be easier or less error-prone to maintain.

PEP-736 also mentions an effect of the new syntax: a new shorthand for dictionary initialization, which – the PEP also points out – is favorably reminiscent of JavaScript’s shorthand properties .

Even Better Object Initialization Shorthand

While the dict initialization shorthand that would result from PEP-736 is nice, I think we could do even better. Motivation:

Many prefer using the { } syntax for initializing objects over the dict() syntax: It would be nice to be able to continue use { } while still benefiting from the spirit of PEP-736.

I am jealous of JavaScript’s object initialization property shorthand

NB: Python cannot adopt the identical syntax from JavaScript because a colonless { } initializer in Python is already spoken for: it is a shorthand for initializing a set() .

*I am still in favor of everything in PEP-736 – I do not here propose to change it or make any part of it unnecessary.

Request for Proposal

I think it would be great if Python had a shorthand for object initialization that is in the spirit of PEP-738 and nearly as ergonomic as JavaScript’s shorthand properties .

I would like to hear the python.org community’s feedback: do you like this idea in principle? Do you have ideas for a reasonable syntax?

Here I’ll share my own proposal (and some thoughts on a few alternatives):

That’s all there is to it!

f-dicts: some more detail

For purpose of illustration, assume the following:

Then, all of these are equivalent:

print(repr(d)) for any of the above prints:

Mixing “shorthand” with longhand in a classic {} initializer is still a syntax error, as it is today:

An opportunity for confusion and mistakes arises when mixing shorthand notation with longhand notation in an f-dict. In the following example:

… which result did do you expect? You could make an argument for either result being understandable:

For the sake of simplicity, I suggest that using computed key names in an f-dict is a syntax error. If you need a computed key name, here are your workarounds:

  • Don’t use an f-dict
  • Add the computed key after the initializer ( d[runtime_key] = 'whatever' ).
  • Unpack the computed key from a {} dict into the f-dict
  • If your desired result was result #1 , simply put quotes around my_second_var :

I suspect that f-dicts are not very useful in the context of a dict comprehension. The variable names typically used within a comprehension are often temporary and/or non-descript. In order to keep the proposal simple, I suggest that if X is a generator expression, then f{X} is a syntax error. I’d like to hear opinions, though.

Unpacking into an f-dict is no different than unpacking into a regular dict.

An f-dict literal f{} creates a normal dict object in memory no later than a normal dict literal {} would. I do not see that the treatment of f{} in the context of pattern matching would be any different than {} .

A downside to the f-dict literal is that it might look too much like a set-initializer. In

an uninformed reader could reasonably assume that they are reading a set-initializer, because it looks nearly identical to one:

But then, the uninformed reader might assume that after s = f"hello {yourname}" , the variable s will contain the text hello {yourname} . Or that s = f"{shutil.rmtree('/')}" would not delete their hard drive. : )

Additionally, I could not imagine (and I tried) any reasonable circumstance under which a hypothetical “f-set” would ever be needed.

Is there any connection between the f in f{} and the f in f"" ?

A connection between the f in f-strings and the f in an f-dict is not obvious. With f-strings, the f is pretty clearly a mnemonic for the concept of f ormatting. The shorthand enabled by f-dict’s f{} syntax might not seem to have any connection to the concept of formatting at all.

There is some commonality, I think, though. Consider

Suffixing, with = , an expression embedded in an f-string via {} also converts a variable name (or even literal program expression code) into (part of) a runtime string. In a similar way, f{var} converts a symbol ( var ) in the program to a string "var" , that is then used as a dict key. I think this is the strongest connection between f in f{} and f in f""

However, I admit that the connection is loose enough that it could be a tough buy for many people.

I considered some alternate syntax variations:

I think this borrows from Ruby and its symbols. It’s [much?] less ambiguous than “Empty Colon Suffix”. That’s a good thing. It has already had a prototype implemented by Atsuo Ishimoto here . I guess my only critique would be that some syntax mistakes or typos in your object literal expression that would previously have been a syntax error, could now become unintentionally valid syntax.

I do like that syntaxes in this style do not introduce a new “type” of expression – at least at the tier of language hierarchy that dictionary literals sit at. You don’t need to learn all the rules for f-dict expressions, you just need to learn what :varname means inside a dict-like / set-like curly brace initializer. A reason to prefer f-dict is, perhaps, that the f-dict declares up front your intent to use “new syntax” and so linters and readers could perhaps be more prepared.

Discussion of Atsuo’s proposal is here: Shorthand notation of dict literal and function call

The empty-equals syntax takes = from kwargs and PEP-736 and allows mixing it in with : elsewhere in the object initializer. It’s way less ambiguous than empty-colon, has cognitive underloading due to the similarity with kwargs, and it keeps the key name on the LHS of the expression (unlike Empty Colon Prefix), which I think is more natural to most readers.

The syntax is maybe “obvious” at first glance. You simply delete the right-hand-side of the “assignment” inside the object expression, remove the quotes, and you’re done, right? Unfortunately things get confusing when you try to hammer out the details of what to do with computed keys. Consider:

It seems sort of unintuitive that the very similar code on lines 3 and 4 end up putting different keys in the dictionary.

I’m not sure why you would prefer this over “Empty Equals”, except that it retains the colon : from the traditional the object expression and combines it with = in the sense of the named-parameter calling convention. Unfortunately, to my mind, the := here doesn’t necessarily read like a single operator, it’s more like the : belongs to the object-literal syntax and indicates a binding of a key to a value, and the = is borrowed from kwargs syntax and indicates that the unquoted symbol will eventually be a string dict key, as in myfunc(a='v') may result in the string key "a" added to the callee’s kwargs dict. Also, := in this context doesn’t seem to share much in common with the side-effect assignment usage of := .

Variation: Empty Left-Facing Walrus

Similar to the above, but =: does not overload the side-effect assignment := operator.

I’d like to hear your thoughts:

  • Do you agree, disagree, or something else?
  • Do you have feedback on f-dict?
  • How about on any of the alternatives?
  • Do you have an alternative?

You can join the existing discussion:

I don’t like f{a, b, c} because that could be the syntax for a frozenset.

How often do people have a use for string-keyed dictionaries, each value in which is exactly the same as its key? Granted they can be mutated afterwards.

Even where such a dict is needed or will be subsequently mutated, and where a set will not suffice, is a simple dictionary comprehension really so bad?

You’re not wrong Mike, that this can initialize some objects, as in Python everything is an object . But it would help people to understand your proposal if you clarify that this only for dicts, not overriding __init__ on object instances of every class.

Related Topics

IMAGES

  1. Operator Overloading in Python (Polymorphism)

    assignment operator overload python

  2. Python: What is Operator Overloading in Python

    assignment operator overload python

  3. What is Operator Overloading in Python (with Examples)

    assignment operator overload python

  4. Python OOP Tutorials

    assignment operator overload python

  5. Python Operator Overloading

    assignment operator overload python

  6. Python Tips Series: Operator Overloading

    assignment operator overload python

VIDEO

  1. Assignment Operator

  2. Assignment Operators in Python Programming Language

  3. How to use assignment operators in #python

  4. THIS IS MY FAVOURITE OPERATOR IN PYTHON #coding #python #codingtips #programminglanguage

  5. assignment overload 🙁😩😞

  6. 013024 Python Operator Precedence

COMMENTS

  1. Is it possible to overload Python assignment?

    Is it possible to overload Python assignment? Ask Question Asked 11 years, 8 months ago Modified 1 year ago Viewed 68k times 112 Is there a magic method that can overload the assignment operator, like __assign__ (self, new_value)? I'd like to forbid a re-bind for an instance:

  2. Operator Overloading in Python

    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. Overloading binary + operator in Python:

  3. Operator and Function Overloading in Custom Python Classes

    Shortcuts: the += Operator Indexing and Slicing Your Objects Using [] Reverse Operators: Making Your Classes Mathematically Correct A Complete Example Recap and Resources Remove ads If you've used the + or * operator on a str object in Python, you must have noticed its different behavior when compared to int or float objects: Python

  4. How to Emulate Assignment Operator Overloading in Python?

    How can you emulate assignment operator overloading in Python? For example... class Example (object): name = String () age = Integer () def __init__ (self,myname,myage): self.name.value = myname self.age.value = myage

  5. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  6. Python Operator Overloading

    The assignment is not necessary. Python also provides you with a list of special methods that allows you to overload the inplace operator: Let's take an example of overloading the += operator.

  7. Python Operator Overloading (With Examples)

    Python Operator Overloading In Python, we can change the way operators work for user-defined types. For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

  8. Python Assignment Operator Overloading

    Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python. Example: overloading assignment operator In the example below, assignment operator (+=) is overloaded.

  9. Beyond the Basics: Mastering Advanced Operator Overloading Techniques

    Augmented assignment operators are used to assign and perform an operation at the same time. Here are some augmented assignment operators and their corresponding magic methods: ... Operator overloading in Python is a powerful mechanism that allows developers to redefine the behavior of standard operators for custom classes. By implementing ...

  10. Operator Overloading in Python

    Operator Overloading is the phenomenon of giving alternate/different meaning to an action performed by an operator beyond their predefined operational function. Operator overloading is also called Operator Ad-hoc Polymorphism. Python operators work for built-in classes. But the same operator expresses differently with different types.

  11. Python Operator Overloading: A Comprehensive Guide

    How to Overload Operators: You must define special methods, commonly referred to as magic methods or dunder methods, which are prefixed and suffixed with double underscores, in order to overload operators. These methods specify how operators behave when used on items from your special class. Example: class Point: def __init__(self, x, y):

  12. Python Operator Overloading

    Modifying the behavior of an operator by redefining the method an operator invokes is called Operator Overloading. It allows operators to have extended behavior beyond their pre-defined behavior. Let us first discuss operators, operands, and their behavior before diving into the operator overloading. Operators and Operands in Python

  13. Python Operator Overloading Tutorial

    What is Python Operator Overloading? Operator overloading in Python is a fascinating feature that allows the same operator to have different meanings based on the context. It's like a chameleon changing its colors according to its surroundings. But instead, here, the operator changes its function depending on the operands.

  14. Python Operator Overloading And Magic Methods

    Operator Overloading In Python. Basically, operator overloading means giving extended meaning beyond their predefined operational meaning. For example, a + operator is used to add the numeric values as well as to concatenate the strings. That's because + is overloaded for int class and str class. But we can give extra meaning to this ...

  15. Operator Overloading in Python

    Operator Overloading is a handy feature in Python that allows us to "overload" or "over-ride" an operator with our own custom code. Operators such as +, -, *, / may not work in certain situations, such as when adding together two objects from custom classes you may have created.. In order to resolve this, we "overload" these operators to ensure it correctly adds the objects in a ...

  16. PDF CHAPTER 13 Operator Overloading: Doing It Right

    • The default handling of augmented assignment operators, like +=, and how to over‐ load them Operator Overloading 101 Operator overloading has a bad name in some circles. It is a language feature that can be (and has been) abused, resulting in programmer confusion, bugs, and unexpected performance bottlenecks.

  17. Operator Overloading in Python [Article]

    Well, thankfully, you can. This practice is called Operator Overloading because you're overloading, or overwriting, how operators work. By "operator", I mean symbols like +, -, and *. Remember back in Object-Oriented Python when we overloaded __init__ () to change how our classes initialized themselves?

  18. Assignment Operators in Python

    1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand. Syntax: x = y + z Example: Python3 a = 3 b = 5 c = a + b print(c) Output: 8 2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand. Syntax:

  19. operator overloading

    61 This question already has answers here : Overriding "+=" in Python? (__iadd__ () method) (4 answers) Closed 4 years ago. I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems: if __add__ mutates self, then z = x + y will mutate x when I don't really want x to be mutated there.

  20. Shorthand Object Initialization

    I think it would be great if Python had a shorthand for object initialization that is in the ... I admit that the connection is loose enough that some might object to the overloading. I considered some alternate syntax variations: ... Similar to the above, but =: does not overload the side-effect assignment := operator. return {my_first_var ...

  21. operator overloading

    The operators in question are called "augmented assignment" operators, so the first place you should look is to put something like python augmented assignment into a search engine. Even without knowing that, something like python operator overloading should give you some relevant results. - Karl Knechtel Apr 14, 2021 at 10:26 Add a comment 1 Answer