Python Decorators: How to Say Answer Quickly

Let's first talk about decorators. You will learn how decorators work and where in your real-world project you can use them. 


Decarators in Python
Python Decorators: How to Say Answer Quickly

Decorators are an interesting and useful feature of Python. If you understand decorators well, you can build a lot of magical features without much effort.

Python Decorators

Decorators are another form of function pointers. They accept a function as an argument, then either wrap the function and return a new function, or modify the inputs or outputs to the function.

Python decorators help you add behavior to functions or objects dynamically without changing the function or object behavior.

Let's say you have a simple function that converts a passed-in string to uppercase and returns the result.


       

def to_uppercase(text):
 """Convert text to uppercase and return to uppercase.""" 
if not isinstance(text, str): 
raise TypeError("Not a string type"
return text.upper() 
>>> text = "Hello World"
 >>> to_uppercase(text) 
HELLO WORLD

How to use Decorators in Python

Basically, a decorator is a wrapper around a function that provides additional functionality to that function. 


It may modify the behavior of the function, such as changing the return type, or it may simply add new abilities to the function that the original writer never considered.

       

def to_uppercase(func):
"""Convert to uppercase and return to uppercase."""

    # Adding this line, will call passed function to get text
text = func()

if not isinstance(text, str):
        raise TypeError("Not a string type")
return text.upper()

def say():
return "welcome"

def hello():
return "hello"

a = to_uppercase(say)
print(a) ==> WELCOME

b = to_uppercase(hello)
print(b) ==> HELLO
References

Comments

Most Popular

7 AWS Interview Questions asked in Infosys, TCS

How to Decode TLV Quickly

Hyperledger Fabric: 20 Real Interview Questions