Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Generator (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Python=== Generators were added to [[Python (programming language)|Python]] in version 2.2 in 2001.<ref name="python"/> An example generator: <syntaxhighlight lang="python"> from typing import Iterator def countfrom(n: int) -> Iterator[int]: while True: yield n n += 1 # Example use: printing out the integers from 10 to 20. # Note that this iteration terminates normally, despite # countfrom() being written as an infinite loop. for i in countfrom(10): if i <= 20: print(i) else: break # Another generator, which produces prime numbers indefinitely as needed. import itertools def primes() -> Iterator[int]: """Generate prime numbers indefinitely as needed.""" yield 2 n = 3 p = [2] while True: # If dividing n by all the numbers in p, up to and including sqrt(n), # produces a non-zero remainder then n is prime. if all(n % f > 0 for f in itertools.takewhile(lambda f: f * f <= n, p)): yield n p.append(n) n += 2 </syntaxhighlight> In Python, a generator can be thought of as an [[iterator]] that contains a frozen [[stack frame]]. Whenever <code>next()</code> is called on the iterator, Python resumes the frozen frame, which executes normally until the next <code>yield</code> statement is reached. The generator's frame is then frozen again, and the yielded value is returned to the caller. PEP 380 (implemented in Python 3.3) adds the <code>yield from</code> expression, allowing a generator to delegate part of its operations to another generator or iterable.<ref name="pep380">[https://www.python.org/dev/peps/pep-0380/ PEP 380 -- Syntax for Delegating to a Subgenerator]</ref> ====Generator expressions==== Python has a syntax modeled on that of [[list comprehension]]s, called a generator expression that aids in the creation of generators. The following extends the first example above by using a generator expression to compute squares from the <code>countfrom</code> generator function: <syntaxhighlight lang="python"> squares = (n * n for n in countfrom(2)) for j in squares: if j <= 20: print(j) else: break </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)