Home > Backend Development > Python Tutorial > What are generators and decorators in Python?

What are generators and decorators in Python?

王林
Release: 2023-09-10 22:49:02
forward
1046 people have browsed it

What are generators and decorators in Python?

In this article, we will explain to you what generators and decorators are in Python.

Generators have been an important part of Python since their introduction in PEP 255.

A generator in Python is a special routine that can be used to control the iterative behavior of a loop. Generators are like functions that return arrays. The generator has a parameter that we can call and generate a sequence of numbers. But unlike functions that return an entire array, generators generate values ​​one at a time, requiring less memory.

Any Python function with the keyword "yield" can be called a generator. A normal python function starts execution from the first line and continues until we receive a return statement or an exception or the function ends, however, any local variables created during the function scope are destroyed and cannot be accessed further. For a generator, when it encounters the yield keyword, the function's state will be frozen and all variables will be stored in memory until the generator is called again.

We can use a generator based on an iterator, or call it explicitly using the "next" keyword.

Usually a generator in Python -

  • Use def keyword definition

  • Use yield keyword

  • may contain multiple revenue keywords.

  • Return an iterator.

Generators are functions that return Iterablegenerator objects. Because the values ​​in the generator object are fetched one at a time rather than the entire list at once, you can use a for loop, next(), or list() function to get the actual values.

Generator function

Generators can be created using generator functions and generator expressions.

A generator function is similar to a regular function, but instead of returning a value, it has the yield keyword.

To create a generator function, add the yield keyword. The following example demonstrates how to write a generator function.

Generator with iterator

Example

# creating a function
def generatorExample():
   yield "T"
   yield "U"
   yield "T"
   yield "O"
   yield "R"
   yield "I"
   yield "A"
   yield "L"
   yield "S"
# calling the generatorExample() function which is created above
result = generatorExample()
# Traversing in the above result(generator object)
for k in result:
   # Printing the corresponding value
   print(k)
Copy after login

Output

T
U
T
O
R
I
A
L
S
Copy after login

Read the output value from the generator

The list(), for-loop and next() methods can be used to read values ​​from the generator object.

Use next() to read the value from the generator object

next() method returns the next item in a list, array, or object. When the list is empty and next() is called, it returns an error with the stopIteration signal. This error indicates that there are no more entries in the list.

Example

# creating a function that accepts a number as an argument
def oddNumbers(num):
   # traversing till that number passed
   for i in range(num):
      # checking whether the iterator index value is an odd number
      if (i%2!=0):
         # getting the iterator index value if the condition is true using the yield keyword
         yield i
# calling the above function to get the odd numbers below 8
result = oddNumbers(8)
# calling the next items in the result list
print(next(result))
print(next(result))
print(next(result))
print(next(result))
# throws an error since the list has no more elements
print(next(result))
Copy after login

Output

1
3
5
7
Traceback (most recent call last):
File "main.py", line 17, in <module>
    print(next(result))
StopIteration
Copy after login

Decorators in Python

Python provides an amazing tool called Decorator for adding functionality to existing code.

This is also called metaprogramming because one part of the program attempts to modify another part of the program at compile time.

The decorator uses a function as a parameter in another function and then calls the function within the wrapping function.

grammar

@tutorials_decorator
def python_decorator():
   print("Hello tutorials Point")
'''Above code is equivalent to -
def python_decorator():
   print("Hello tutorials Point")
python_decorator = tutorials_decorator(python_decorator)'''
Copy after login

The tutorials_decorator here is a callable function that adds some code on top of another callable function python_decorator and returns the wrapper function.

Example

Herefunc is the decorated function, python_decorator is the function used to decorate it

# defining a decorator
def python_decorator(func):
   def wrapper():
      print("Text before calling the function")
      func()
      print("Text after calling the function")
   return wrapper
def tutorials_decorator():
   print("Hello tutorials Point!!!")
tutorials_decorator = python_decorator(tutorials_decorator)
tutorials_decorator()
Copy after login

Output

Text before calling the function
Hello tutorials Point!!!
Text after calling the function
Copy after login
Copy after login

python_decorator(func) - This is a decorator function; it accepts another function as an argument and "decorates" it, meaning it modifies it and returns the modified version.

wrapper - We define another inner function called wrapper inside the decorator function. This is the actual function that is modified by wrapping the passed function func.

The wrapper function is returned by the decorator.

tutorials_decorator - This is a normal function that we need to decorate. Here just print a simple statement.

Syntax Decorator

The decorator pattern described above is popular in the Python community, but it is a bit complicated. We have to write the function name three times, and the decoration is hidden under the function definition.

Therefore, Python has added a new way to use decorators by using the @ symbol to contain syntactic sugar.

grammar

@decorator
def func(arg1, arg2, ...):
   pass
Copy after login

Syntactic sugar is syntax used in programming languages ​​to make content easier to read or express.

Example

The following example performs the same operation as the previous example -

# defining a decorator
def python_decorator(func):
   def wrapper():
      print("Text before calling the function")
      func()
      print("Text after calling the function")
   return wrapper
@python_decorator
def tutorials_decorator():
   print("Hello tutorials Point!!!")
tutorials_decorator()
Copy after login

Output

Text before calling the function
Hello tutorials Point!!!
Text after calling the function
Copy after login
Copy after login

Same as the previous example, the only difference is that we use @python_decorator instead of

tutorials_decorator = python_decorator(tutorials_decorator)
Copy after login

in conclusion

In this article, we took a brief look at generators and decorators in Python. We also demonstrated how to use generators and decorators while writing code.

The above is the detailed content of What are generators and decorators in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template