Python lazy evaluation
last modified November 30, 2026 Python 3.15
In this article we show where Python evaluates expressions lazily and how to use it.
Lazy evaluation delays the computation of a value until the
value is needed. If it is never needed, it is never computed. The
opposite is eager evaluation, which computes a value as soon
as the expression is reached. Python is an eager language: expressions
are evaluated immediately, and function arguments are evaluated before
the function is called. Laziness is available in specific places: the
and and or operators, conditional expressions,
iterators, and since recent versions also annotations and imports.
Lazy evaluation saves work and memory and allows infinite sequences. Its cost is that the time of evaluation becomes less obvious, so side effects and errors happen later than one might expect. Generators, the main tool for writing our own lazy code, are covered in detail in Python generators.
Eager evaluation
To see when expressions run, we use a helper function that prints its name before it returns a value. In a function call, all arguments are evaluated first.
def value(name, v):
print(f'evaluating {name}')
return v
def add(a, b):
print('add called')
return a + b
print(add(value('a', 1), value('b', 2)))
Both arguments are evaluated, from left to right, before the body of
add starts. The function receives finished values; it has
no way to skip or delay an argument.
$ python eager_args.py evaluating a evaluating b add called 3
Short-circuit operators
The and and or operators evaluate their right
operand only when it is needed. If the left operand already decides the
result, the right one is skipped.
def value(name, v):
print(f'evaluating {name}')
return v
print(value('a', False) and value('b', True))
print('---')
print(value('c', True) or value('d', False))
print('---')
print(value('e', True) and value('f', 0))
A false left operand decides an and expression, so
b is never evaluated. A true left operand decides an
or expression, so d is skipped. In the last
case the left operand is true and the right one must be evaluated. Note
that both operators return one of their operands, not necessarily
True or False: the last expression gives
0.
$ python short_circuit.py evaluating a False --- evaluating c True --- evaluating e evaluating f 0
Guards and defaults
Short-circuiting is used to guard an expression that would fail, and to provide a default value for an empty one.
users = [
{'name': 'Peter', 'tags': ['admin', 'dev']},
{'name': 'Lucy', 'tags': []},
{'name': '', 'tags': ['dev']},
]
for user in users:
first_tag = user['tags'] and user['tags'][0]
name = user['name'] or 'anonymous'
print(f'{name}: {first_tag or "no tags"}')
empty = []
print(len(empty) > 0 and empty[0] > 10)
The expression user['tags'] and user['tags'][0] indexes the
list only if it is not empty; for an empty list it returns the empty
list, and the or in the f-string turns it into a message.
The or 'anonymous' part replaces an empty name. In the last
line, the comparison empty[0] > 10 would raise an
IndexError, but it is never evaluated. Remember that
or replaces all false values, including 0 and
'', not only None.
$ python guards.py Peter: admin Lucy: no tags anonymous: dev False
Conditional expressions
The conditional expression x if condition else y evaluates
the condition and then only one of the two branches.
def cheap():
print('cheap branch')
return 'cached'
def expensive():
print('expensive branch')
return 'computed'
for hit in [True, False]:
result = cheap() if hit else expensive()
print(result)
In each iteration only one function is called. The branch that is not selected is never computed, which makes the conditional expression safe for branches that are costly or would fail.
$ python conditional_expr.py cheap branch cached expensive branch computed
Eager default values
Because arguments are evaluated eagerly, a default value passed to a
method is computed even when it is not used. A common case is the
get method of a dictionary.
config = {'port': 8080}
def load_default_port():
print('reading defaults file')
return 80
port = config.get('port', load_default_port())
print(port)
print('---')
port = config['port'] if 'port' in config else load_default_port()
print(port)
The key exists, yet the program reads the defaults file, because
load_default_port() is evaluated before get is
called. The same applies to setdefault. If the default is
expensive, we test for the key first, so the conditional expression
calls the function only when the key is missing.
$ python get_default.py reading defaults file 8080 --- 8080
Passing a function instead of a value
A general way to delay a computation is to pass a function that computes the value instead of the value itself. The receiver calls it only when it needs the result.
def get_or_create(cache, key, factory):
if key not in cache:
cache[key] = factory()
return cache[key]
def build_report():
print('building report')
return 'report data'
cache = {}
print(get_or_create(cache, 'report', build_report))
print(get_or_create(cache, 'report', build_report))
The get_or_create function receives build_report
without calling it. It calls the factory only when the key is missing,
so the report is built once. The defaultdict class from the
collections module works the same way: it takes a factory
and calls it for missing keys; see Python
collections.
$ python factory.py building report report data report data
A lazy range
The range object does not store its numbers. It keeps the
start, stop, and step, and computes any item on request.
r = range(0, 10 ** 18, 3) print(len(r)) print(r[1_000_000]) print(r[-1]) print(999_999_999_999_999 in r) print(1_000_000_000_000_000 in r) print(r[10:20:2])
The range describes over 333 quadrillion numbers, but the range object takes
only 48 bytes. Its length, any item, and the result of the
in test are computed with arithmetic, without generating
the numbers. Slicing a range also gives a new range, not a list.
$ python lazy_range.py 333333333333333334 3000000 999999999999999999 True False range(30, 60, 6)
Lazy built-in iterators
The map, filter, zip, and
enumerate functions return lazy iterators. Creating them
does no work; each item is computed when it is requested.
def double(x):
print(f'doubling {x}')
return x * 2
doubled = map(double, [1, 2, 3, 4])
print('map created')
print(next(doubled))
print(next(doubled))
print('rest:', list(doubled))
The output shows that double is not called when the map
object is created. Each next call computes exactly one
item, and the list call computes the rest. A lazy iterator
is used up after one pass; see Python
iterators.
$ python lazy_map.py map created doubling 1 2 doubling 2 4 doubling 3 doubling 4 rest: [6, 8]
Stopping early
The biggest saving comes when we do not need all results. A list comprehension computes every item; a generator expression computes items only until we stop asking.
calls = 0
def is_slow(ms):
global calls
calls += 1
return ms > 500
times = [120, 80, 950, 300, 640, 210, 75, 890]
slow = [t for t in times if is_slow(t)]
print(slow[0], calls)
calls = 0
slow = (t for t in times if is_slow(t))
print(next(slow), calls)
calls = 0
print(any(is_slow(t) for t in times), calls)
We look for the first response time above 500 ms and count the calls of
the is_slow function. The list comprehension checks all
eight values even though we use only the first match. The generator
expression stops after the third value, and so does any,
which returns as soon as it finds a true item. The more data there is,
the bigger the difference.
$ python first_match.py 950 8 950 3 True 3
Errors appear later
With lazy evaluation, an error in the data is not detected when the iterator is created, but only when the bad item is reached.
values = ['10', '20', 'x', '40']
numbers = map(int, values)
print('map created, no error yet')
for n in numbers:
print(n)
Creating the map object succeeds, and the first two numbers are printed
before the conversion of 'x' fails. The traceback points to
the for loop, not to the line where the map object was
created. When data must be validated up front, or when it is important
that either all items or none are processed, eager evaluation with a
list is the safer choice.
$ python late_errors.py
map created, no error yet
10
20
Traceback (most recent call last):
File "/home/user/python/late_errors.py", line 6, in <module>
for n in numbers:
^^^^^^^
ValueError: invalid literal for int() with base 10: 'x'
Live dictionary views
The keys, values, and items
methods of a dictionary return views, not copies. A view reads the
dictionary each time it is used, so it always reflects the current
content.
stock = {'apples': 10, 'pears': 4}
names = stock.keys()
amounts = stock.values()
print(names, amounts)
stock['plums'] = 25
del stock['pears']
print(names, amounts)
print(sum(amounts))
The views are created once, at the beginning. After we add and delete
items, the same views show the new content, and sum adds up
the current values. To keep a snapshot, we must copy the view, for
example with list(stock.keys()).
$ python live_views.py dict_keys(['apples', 'pears']) dict_values([10, 4]) dict_keys(['apples', 'plums']) dict_values([10, 25]) 35
Lazy attributes with cached_property
The functools.cached_property decorator turns a method into
an attribute that is computed on first access and then stored in the
instance.
from functools import cached_property
class Document:
def __init__(self, text):
self.text = text
@cached_property
def word_count(self):
print('counting words')
return len(self.text.split())
doc = Document('an old falcon flies over the dark forest')
print('document created')
print(doc.word_count)
print(doc.word_count)
del doc.word_count
print(doc.word_count)
Creating the document does not count the words. The first access to
word_count runs the method; the second one returns the
stored value. Deleting the attribute clears the cache, so the next
access computes the value again. This is useful for expensive values
that are not always needed. The related
property decorator recomputes
its value on every access.
$ python cached_attr.py document created counting words 8 8 counting words 8
Deferred annotations
Since Python 3.14, annotations of functions and classes are evaluated lazily. They are stored as code and evaluated only when they are requested.
import annotationlib
def area(shape: Shape) -> float:
return shape.width * shape.height
print('function defined')
print(annotationlib.get_annotations(area, format=annotationlib.Format.STRING))
class Shape:
def __init__(self, width, height):
self.width = width
self.height = height
print(area.__annotations__)
print(area(Shape(3, 4)))
The area function refers to the Shape class,
which is defined later. In Python 3.13 and earlier, the
def statement would fail with a NameError.
Now the definition succeeds. The annotationlib module can
read the annotations as strings before the class exists. Once
Shape is defined, accessing __annotations__
evaluates the annotations to real objects.
$ python annotations_later.py
function defined
{'shape': 'Shape', 'return': 'float'}
{'shape': <class '__main__.Shape'>, 'return': <class 'float'>}
12
Lazy imports
Python 3.15 adds the lazy import statement. The module is
not loaded when the statement runs, but on the first use of its name.
This shortens the start-up time of programs that import many modules
but use only some of them in a given run.
print('reports: loading a large module')
def monthly():
return 'monthly report'
The reports module stands for a module that is slow to
load. It prints a message when it is loaded, so we can see the moment of
loading.
import sys
lazy import reports
print('program started')
print('reports' in sys.modules)
if len(sys.argv) > 1:
print(reports.monthly())
print('reports' in sys.modules)
The program uses the module only when it gets a command-line argument.
Without the argument, the module is never loaded. With the argument,
the first access to reports.monthly loads the module, and
then it appears in sys.modules. More on imports is in
Python modules.
$ python lazy_module.py program started False
$ python lazy_module.py monthly program started False reports: loading a large module monthly report True
Source
Boolean operations, functools.cached_property, PEP 649 – Deferred evaluation of annotations, PEP 810 – Explicit lazy imports
In this article we have compared eager and lazy evaluation and used
short-circuit operators, conditional expressions, default values
computed on demand, lazy ranges and iterators, live dictionary views,
cached_property, deferred annotations, and lazy imports.
See also Python generators,
Python iterators,
Python infinite iterators,
and Python chain.
Author
List all Python tutorials.