Dispatch Decorator in Python
Last Updated :
08 May, 2020
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.
Example:
def hello_decorator(func):
def inner1():
print ( "Hello, this is before function execution" )
func()
print ( "This is after function execution" )
return inner1
def function_to_be_used():
print ( "This is inside the function !!" )
function_to_be_used = hello_decorator(function_to_be_used)
function_to_be_used()
|
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
Dispatch Decorator
A Dispatch decorator is used to select between different implementations of the same abstract method based on the signature, or list of types.
Example:
from multipledispatch import dispatch
@dispatch ( int )
def func(x):
return x * 2
@dispatch ( float )
def func(x):
return x / 2
print (func( 2 ))
print (func( 2.0 ))
|
Output:
4
1.0
In the above example, the @dispatch(int)
statement suggests that the Dispatcher ‘func’ is created and then allocates the ‘int’ type as the key and dispatcher ‘func’ as the value and allocates it to the ith index in the namespace (dictionary).
Now you all must be wondering what is a namespace? Don’t worry let’s have a look at the namespace.
Namespace
A namespace is nothing but a dictionary that is used by the dispatch decorator. The dispatch decorator creates a dispatcher object with the name of the function and stores this object as a key-value pair. This dictionary is used to map a functions like func
in the above example to a dispatcher object like Disptacher('func')
.
By default, the namespace used is the global namespace in multipledispatch.core.global_namespace
. For additional security, one can establish their own namespaces using a dictionary.
Example:
from multipledispatch import dispatch
nsp = {}
@dispatch ( int , namespace = nsp)
def func(x):
return x * 2
@dispatch ( float , namespace = nsp)
def func(x):
return x / 2
print (func( 2 ))
print (func( 2.0 ))
print (nsp)
|
Output:
4
1.0
{'func': <dispatched func>}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...