NotImplemented and Reflection Functions in Python

We know that a function or method will:

  • Return some result, or
  • Raise an exception if it cannot find the result

But there is a third thing a function can return and that is NotImplemented. The simple meaning of return NotImplemented by a function is that the function is declaring that it cannot find the result but instead of raising the exception, it will transfer the control to another function, hoping that the other function will get the result. The other function is known as Reflection Function.

Example case that can be solved using NotImplemented and Reflection Function:

We will explore the whole idea in context to Object Oriented Programming and associated Magic Methods (also known as special methods or dunder methods) which are used for different special functionalities and we will just see the ones used to define the support for different operator (e.g. +,-,* etc.) for objects of one class.

Let’s see this simple Point class defined for the points on XY plane:

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return f'({self.x},{self.y})'

p1=Point(3,4)
print(p1)

The __str__ method is defined for the proper representation of the point object and the last print statement will print the point as (3,4).

If we want to define a function for the addition of two point objects, it can be done as:

def addPoints(self,other):
        return Point(self.x+other.x,self.y+other.y)

And then we can use it as:

p1=Point(3,4)
p2=Point(1,1)
p3=p1.addPoints(p2)
print(p3)

This will display (4,5) as output.

But it will be better if instead of using a custom named function like addPoints, we could directly apply + operator like we do for simple numbers and a few other data types e.g. 4+5. At present if we use + operator on two point objects as:

p1=Point(3,4)
p2=Point(1,1)
p3=p1+p2

It will generate following error which is self-explanatory:

TypeError: unsupported operand type(s) for +: ‘Point’ and ‘Point’

If we change the name of the function addPoints to __add__ which is a magic method, the + operator applied between two point objects will call this method.
See the complete code here:

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return f'({self.x},{self.y})'
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)

p1=Point(3,4)
p2=Point(1,1)
p3=p1+p2
print(p3)

And the output will be (4,5).

We have special methods for other operators too e.g. __sub__ is for subtraction ( - ), __mul__ is for multiplication ( * ), __div__ is for division( / ) and a few more.

In fact, when we apply + operator between any data types, interpreter actually executes __add__ method on those e.g. for 3+4, interpreter will execute 3.__add__(4) and the method __add__ is defined in int class for addition of two integers. Similarly, if a and b are two lists, a+b will result into a.__add__(b) and __add__ is defined inside list class as concatenation of the lists.

Now let’s define __mul__ for the Point class but not for the multiplication of two point objects but to multiply the Point object with a number, resulting into a new point with scaled x and y components. It will be done by adding __mul__ method as shown here:

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return f'({self.x},{self.y})'
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,num):
        return Point(self.x*num,self.y*num)

p1=Point(3,4)
p2=p1*2
print(p2)

The output will be (6,8).

But instead of p1*2 if we execute 2*p1, then instead of getting the same result, we get an error as:

TypeError: unsupported operand type(s) for *: ‘int’ and ‘Point’

This is something we will resolve using the concept of NotImplemented and Reflection Function.

What happens when a function returns NotImplemented:

When a function returns NotImplemented, interpreter will run the reflection function associated with that function after flipping the input arguments. For example, if original function has input arguments as a and b, at returning NotImplemented, interpreter will run the associated reflection function on b and a.

Second important thing is that the reflection functions associated with different functions are predefined in Python and you cannot make some function as reflection of some other function by your own. The reflection function of __add__ is __radd__, reflection function of __mul__ is __rmul__ and so on for different magic methods.

So, lets see what happened when interpreter executed 2*p1 in above program.
As described earlier that 2*p1 will result into 2.__mul__(p1), so interpreter will apply __mul__ on 2 which is an integer. Therefore, interpreter will search for __mul__ method inside int class. Interpreter will find the method in int class but that method defines multiplication between two integers and may be between an integer and some other data type but not between an integer and the Point class object. And in such cases (unsupported datatype), the __mul__ of int class returns NotImplemented.
With NotImplemented returned, interpreter will run the reflection method i.e. __rmul__ on flipped input arguments as p1.__rmul__(2). And you can see that the method is applied on p1 which is Point class object and hence interpreter will search for this method (__rmul__) in Point class and will fail since this method is not defined inside Point class. So it will return back to the original function (of int class) and will generate this error:

TypeError: unsupported operand type(s) for *: ‘int’ and ‘Point’

The whole process is given here step by step for further clarification:

  1. 2*p1 will result into 2.__mul__(p1) and Interpreter searches for __mul__ in int class.
  2. __mul__ in int class returns NotImplemeted for unsupported types of operands.
  3. This results into execution of reflection function as p1.__rmul__(2).
  4. Interpreter will look for __rmul__ inside Point class because p1 is Point class object.
  5. When failed to find __rmul__ in Point class, interpreter will go back to int class and generate the error.

So if you have followed along these steps, you probably have figured out the solution which is that we must define __rmul__ in Point class, so that p1.__rmul__(2) should get executed.

What should be inside this function?

p1.__rmul__(2) means that self is p1 and second input argument is 2 and we need to return a new point with scaled xy coordinates. So, we should have __rmul__ defined as:

def __rmul__(self,num):
        return Point(self.x*num,self.y*num)

But this is exactly what __mul__ does, and hence we can also do as:

def __rmul__(self,num):
        return self*num

Above return statement with multiplication will call the __mul__ method.
Even a better approach will be to just declare:

__rmul__=__mul__

Because the function are also Objects and we are saying that __rmul__ is referring to same object as __mul__.
The complete code will be:

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return f'({self.x},{self.y})'
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,num):
        return Point(self.x*num,self.y*num)
    __rmul__=__mul__
p1=Point(3,4)
p2=2*p1
print(p2)

And now we will get the correct output as (6,8).

You can see that it is just the one last line added in Point class i.e. __rmul__=__mul__ and it resolved a big problem. And that is all because of the power of NotImplemented and Reflection Function support of Python.

Please don’t forget to subscribe: Learning Orbis

You can find further detail with more practice examples in this video:

If you need more detail on Magic Methods, you can find that in the following videos:

#notimplemented #reflection #python #programming #oop

What is GEEK

Buddha Community

NotImplemented and Reflection Functions in Python
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips