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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Using Python Libraries in Java
  • Start Coding With Google Cloud Workstations
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why I Started Using Dependency Injection in Python

Trending

  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • Docker Base Images Demystified: A Practical Guide
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  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
40.6K 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

  • Using Python Libraries in Java
  • Start Coding With Google Cloud Workstations
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why I Started Using Dependency Injection in Python

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!