Side-effects [was Re: I am out of trial and error again Lists]

Steven D'Aprano steve+comp.lang.python at
Sun Oct 26 07:12:21 CET 2014

Chris Angelico wrote:

> On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody <rustompmody at>
> wrote:
>> Its generally accepted that side-effecting functions are not a good idea
>> -- typically a function that returns something and changes global state.
> Only in certain circles. Not in Python. There are large numbers of
> functions with side effects (mutator methods like list.append,
> anything that needs lots of state like random.random, everything with
> external effect like I/O, heaps of stuff), and it is most definitely
> not frowned upon.

Hmmm. You might be overstating it a tad. You are absolutely correct that
Python is not a strict functional language with no side-effects.

However, mutator methods on a class don't change global state, they change
the state of an instance. Even random.random and friends don't change
global state, they change a (hidden) instance, and you can create your own
instances when needed. That gives you the convenience of pseudo-global
state while still allowing the flexibility of having separate instances.
Even global variables in Python are global to the module, not global to the
entire application.

So although Python code isn't entirely side-effect free, the general advice
to avoid writing code that relies on global state and operates via
side-effect still applies. To take an extreme example, we do this:


not this:

LEN_ARGUMENT = something

We *could* write code like that in Python, but as a general rule we don't.
If we did, it would be frowned upon. I would say that Python is a pragmatic
language which uses whatever idiom seems best at the time, but over all it
prefers mutable state for compound objects, prefers immutable state for
scalar objects (like numbers), and discourages the unnecessary use of
global mutable state.


More information about the Python-list mailing list