liveBook · Manning

Side effect

As explained in Python Workout, Second Edition

A side effect is an observable change or interaction produced by an operation in addition to its returned value.

A side effect is an observable change or interaction produced by an operation in addition to its returned value. In Python, a loop can be useful for what its commands do rather than what it returns. section 8.19

Recognize side effects when:

  • A file loop assigns each line to a variable so the final assignment remains available after the loop. section 6.3
  • A regular for loop inserts records into a database, making the external change more important than the loop's return value. section 8.19
  • A comprehension constructs a new collection from expression values, so it is preferable when the result—not side effects—is the goal. section 8.19

Retaining the final file line

for one_line in open(filename): pass print(one_line) The loop's useful effect is assigning each line to one_line; after iteration, the final assignment remains available for printing. section 6.3

How Python Workout, Second Edition covers it

How deep it goes
Explains side effects through file-loop assignments and database insertion, without developing a formal taxonomy of effects.
Examples
Uses final-line capture during file iteration and database insertion as concrete side-effect examples.
What it assumes
Assumes familiarity with Python loops, iterable file objects, assignments, returned values, and comprehensions.
What you can do after
Apply it via Python for loops when commands or external changes matter more than a comprehension's returned collection.
How it connects
Connects side effects with for loops, return values, list comprehensions, file iteration, and database insertion.

Also explained in

Compare how 24 books explain side effect →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.