How does python distinguish return and yield

1. Description

Return has always been, there is no big difference in each language, so I won't say more. (The return of the shell language is the exit status, and the difference may be relatively large. If you are interested, please refer to "Linux Shell Function Definition and Calling")

I first saw which language used to adjust the thread priority of yield. I can't remember clearly, but the yield should be different from the yield in python.

The first time I saw yield in Python was when I used the scrapy framework to write crawlers. I also saw the usage of yiled before, but I can't remember it. I went to see it again today. Basically, I talked about some of the troubles of the Fibonacci sequence. I wrote a section of the program myself and studied it. Here is a note.

Two, the similarities and differences between return and yield

Common point: return and yield are both used to return values; the role of return and yield is the same in the scenario of returning all values at once.

Difference: If the data to be returned is iterator type data (such as lists, tuples) generated by loops such as for, return can only be returned once outside the loop, and yeild can be returned element by element inside the loop. Below we illustrate this difference with an example.

3. Example description

3.1 return version

The sample code is as follows:

classTestYield:
 def gen_iterator(self):
 result_list =[]for j inrange(3):print(f"gen_iterator-{j}")
 result_list.append(j)
 # return is outside the loop, and returns once after the variable is completely generated
 return result_list

 def call_gen_iterator(self):
 # After executing the following sentence, result_list is directly the result of completion[0,1,2]
 result_list = self.gen_iterator()for i in result_list:print(f"call_gen_iterator-{i}")if __name__ =="__main__":
 obj =TestYield()
 obj.call_gen_iterator()

The execution result is as follows, you can see that after executing the lower-level function at one time, the complete iterator type return value result_list is generated, and it is returned to the upper-level function at one time:

3.2 yield version

The sample code is as follows:

classTestYield:
 def gen_iterator(self):for j inrange(3):print(f"do_something-{j}")
 # yield is inside the for loop
 yield j

 def call_gen_iterator(self):
 # yield is not a direct return[0,1,2], After executing the following sentence result_list has no value
 result_list = self.gen_iterator()
 # i gen is triggered every time a piece of data is requested_iterator generates a data
 for i in result_list:print(f"call_gen_iterator-{i}")if __name__ =="__main__":
 obj =TestYield()
 obj.call_gen_iterator()

The execution result is as follows, you can see that the upper and lower functions are alternated, that is, the upper function requests to iterate a value before the lower function generates a value and returns this value immediately:

3.3 The meaning of yield

As can be seen from the two subsections above, although the execution order of return and yield is different, the whole thing to be done is the same, so using yield will not be faster than return, and we can even guess that because yield always occurs in context Switching will be slower in speed, so speed is not the meaning of yield.

The main difference between them is that yiled must iterate to which element and that element is generated instantly, while return uses an intermediate variable result_list to save the return value. When the length of result_list is very long and the content of each constituent element is large, it will cost more At this time, yield has an advantage over return.

Four, nested use of yield and return

classTestYield:
 def gen_iterator(self):for j inrange(3):print(f"do_something-{j}")
 # yield is inside the for loop
 yield j

 def gen_iterator_middle(self):print(f"gen_iterator_middle")
 # The return is the handle of the iterator, so it is understandable that adding a layer of return does not affect
 return self.gen_iterator()

 def call_gen_iterator(self):
 # yield is not a direct return[0,1,2], After executing the following sentence result_list has no value
 result_list = self.gen_iterator_middle()
 # i gen is triggered every time a piece of data is requested_iterator generates a data
 for i in result_list:print(f"call_gen_iterator-{i}")if __name__ =="__main__":
 obj =TestYield()
 obj.call_gen_iterator()

The above is the detailed content of how python distinguishes return and yield. For more information about python return and yield, please follow other related articles on 179885.Com!

https://www.179885.com/python/433122.html

Recommended Posts

How does python distinguish return and yield
How does Python output integers
How does python output backslashes
How does python update packages
How does python perform matrix operations
How does Python list update value
How does python change the environment
How does python call java classes
How does python import dependency packages
How does python enter interactive mode
How does Python generate xml files
How to write return in python
How does python determine prime numbers
How to use and and or in Python
How does python improve the calculation speed
How does python call its own function
How does Python handle the json module
How does CentOs7 fix MBR and GRUB?
How does Python call cmd using OS modules
Python and Go
How to delete files and directories in python
How to read and write files with Python
How does Python store data to json files
How does python call the key of a dictionary
How does python handle the program cannot be opened
How does python judge the module installation is complete
Python introspection and reflection
[python] python2 and python3 under ubuntu
Python deconstruction and packaging
How python was invented
Python3 configuration and entry.md
How Python parses XML
How long does it take to learn python by myself?