yield
The keyword that makes a function a generator: yield value hands one value to the caller and pauses until the next one is asked for.
In more detail
Local variables keep their values between yields. When the function body ends, the generator stops and the for loop using it finishes. Testing tools such as pytest also use yield to split a fixture into setup code before it and teardown code after it.
Related terms
- generator — A function that can pause and resume, producing a series of values one at a time with yield, each only when it is requested.
- iterator — An object that produces the items of a sequence one at a time, on request, instead of all at once.
- fixture — A named piece of setup, defined with @pytest.fixture, that a test receives by listing the fixture's name as a parameter.
- setup and teardown — The work done before a test to prepare what it needs, and after it to clean up, such as closing files or stopping containers.
Taught in
- Literals, Identifiers And Keywords — Hands-on Python: Complete Video Course & Book
- Chapter Three In One Sitting — Hands-on Python: Complete Video Course & Book
- Iterators And Generators — Hands-on Python: Complete Video Course & Book
- Fixtures And Their Scope — Automated Testing, TDD & Quality Engineering
- Integration Testing With Containers — Automated Testing, TDD & Quality Engineering
- Collections Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Functions, Return Values And Recursion — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Functions And Exceptions Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Lambdas, map() And filter() — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Generators And Iterators — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep