DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • DuckDB for Python Developers

Trending

  • Microservices: Externalized Configuration
  • Optimizing Databricks Spark Pipelines Using Declarative Patterns
  • YOLOv5 PyTorch Tutorial
  • Design Patterns for GenAI Creative Systems in Advertising
  1. DZone
  2. Coding
  3. Languages
  4. When to Use Yield Instead of Return in Python

When to Use Yield Instead of Return in Python

Many Python developers use yield in their code without considering whether they really need to. This article explains when you it actually should be used.

By 
Orcun Yilmaz user avatar
Orcun Yilmaz
·
Jul. 17, 17 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
41.0K Views

Join the DZone community and get the full member experience.

Join For Free

Lately, I’ve seen so many projects that are using yield keyword in the structure, whether or not it was needed.

So I’ve decided to look into this a bit and wanted to share some information about it with you guys.

First things first.

The yield statement is only used when defining a generator function and is only used in the body of the generator function.

Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

The yield statement suspends the function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it is left off. When resumed, the function continues the execution immediately after the last yield run. This allows its code to produce a series of values over time rather them computing them all at once and sending them back like a list.

Let’s see this with an example:

def simpleGeneratorFun():
    yield 1
    yield 2
    yield 3

for value in simpleGeneratorFun():
    print(value)

The output of this code will be:

1
2
3

When a yield statement is executed, the state of the generator is frozen and the value of expression_list is returned to next()'s caller. By "frozen," we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. Enough information is saved so that the next time next() is invoked, the function can proceed exactly as if the yield statement were just another external call.

yield-vs-return-in-python

The yield statement is not allowed in thetry  clause of a try ... finally construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the finally block will ever get executed.

return sends a specified value back to its caller, whereas yield can produce a sequence of values.

We should use yield when we want to iterate over a sequence but don’t want to store the entire sequence in memory.

yield is used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

def nextSquare():
    i = 1;
    # An Infinite loop to generate squares 
    while True:
        yield i*i                
        i += 1  # Next execution resumes 
                # from this point     

for num in nextSquare():
    if num > 100:
         break   
    print(num)

The output of this code will be:

1
4
9
16
25
36
49
64
81
100

And that's it!

Python (language)

Published at DZone with permission of Orcun Yilmaz. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • DuckDB for Python Developers

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook