Tag: method

Python- Decorator functions

Decorators are very useful for refactoring or debugging the code.

Decorators are used to but not limited to do the following –

  • validate the arguments
  • modiy the arguments
  • modify the returned objects
  • message logging
  • caching

See below code snippet calls the log function to the decorator method which returns the log function.

Other way to perform the same is by decorating the method with @decorator method which widely in Python

The above example can be rewritten with following code snippet. Here the calling function is decorated with log function which returns

Arguments passed to the deocrated function can also be made available to the decorator function using *args and **kwargs

See below example for same. Here the decorator calls the decorated function and prints the same. This way you can log the execution of decorated function. Log the time the parameters, output and time taken to execute the fucntion.

This way decorator function can be made global.

Python – Magic methods

Did you know Python internally uses magic method for operators e.g. for + operator uses __add__() method

number = 10
print(number + 10)

#internally calls __add__() method

print(number.__add__(20))

The “+” operator depends on the type of the values been added i.e. int, float,string etc.

Now adding 2 integer or float values will add the values while for string it will concatenate the string.

But what about the objects? See below example when 2 objects are added it throws error.

This can be resolved with the magic method i.e. using __add__()

See below example. Here the “+” operator when used on objects calls the __add__() method.

How to know such magic methods for various types? Use help() method

help() method displays documentation for the

help(int)
help(str)
help(float)
help(bool)

Here is a list of operators to magic method mapping-

Comparision methods

OperatorMagic methodImplementation meaning or purpose
==__eq__(self, other)equality operator
!=__ne__(self, other)inequality operator
<__lt__(self, other)less-than operator
>__gt__(self, other)greater-than operator
<=__le__(self, other)less-than-or-equal-to operator
>=__ge__(self, other)greater-than-or-equal-to operato

Unary Operators

OperatorMagic methodImplementation meaning or purpose
+__pos__(self)unary positive, like a = +b
__neg__(self)unary negative, like a = -b
abs()__abs__(self)behavior for abs() function
round(a, b)__round__(self, b)behavior for round() function

Binary Operators

OperatorMagic methodImplementation meaning or purpose
+__add__(self, other)addition operator
__sub__(self, other)subtraction operator
*__mul__(self, other)multiplication operator
//__floordiv__(self, other)integer division operator
/__div__(self, other)division operator
%__mod__(self, other)modulo operator
**__pow__(self, other)exponential (power) operator

Unary Operators and assignments

OperatorMagic methodImplementation meaning or purpose
+=__iadd__(self, other)addition and assignment operator
-=__isub__(self, other)subtraction and assignment operator
*=__imul__(self, other)multiplication and assignment operator
//=__ifloordiv__(self, other)integer division and assignment operator
/=__idiv__(self, other)division and assignment operator
%=__imod__(self, other)modulo and assignment operator
**=__ipow__(self, other)exponential (power) and assignment operator

Type conversion methods

FunctionMagic methodImplementation meaning or purpose
int()__int__(self)conversion to integer type
float()__float__(self)conversion to float type
oct()__oct__(self)conversion to string, containing an octal representation
hex()__hex__(self)conversion to string, containing a hexadecimal representation

Object introspection

FunctionMagic methodImplementation meaning or purpose
str()__str__(self)responsible for handling str() function calls
repr()__repr__(self)responsible for handling repr() function calls
format()__format__(self, formatstr)called when new-style string formatting is applied to an object
hash()__hash__(self)responsible for handling hash() function calls
dir()__dir__(self)responsible for handling dir() function calls
bool()__nonzero__(self)responsible for handling bool() function calls

Object retrospection

FunctionMagic methodImplementation meaning or purpose
isinstance(object, class)__instancecheck__(self, object)responsible for handling isinstance() function calls
issubclass(subclass, class)__subclasscheck__(self, subclass)responsible for handling issubclass() function calls

Object attribute access

Expression exampleMagic methodImplementation meaning or purpose
object.attribute__getattr__(self, attribute)responsible for handling access to a non-existing attribute
object.attribute__getattribute__(self, attribute)responsible for handling access to an existing attribute
object.attribute = value__setattr__(self, attribute, value)responsible for setting an attribute value
del object.attribute__delattr__(self, attribute)responsible for deleting an attribute

Methods allowing access to containers

Expression exampleMagic methodImplementation meaning or purpose
len(container)__len__(self)returns the length (number of elements) of the container
container[key]__getitem__(self, key)responsible for accessing (fetching) an element identified by the key argument
container[key] = value__setitem__(self, key, value)responsible for setting a value to an element identified by the key argument
del container[key]__delitem__(self, key)responsible for deleting an element identified by the key argument
for element in container__iter__(self)returns an iterator for the container
item in container__contains__(self, item)responds to the question: does the container contain the selected item?

References – https://docs.python.org/3/reference/datamodel.html#special-method-names