help: Unit test fixture returning the same object

Peter Otten __peter__ at web.de
Wed Aug 4 16:32:08 EDT 2004


Michael McCracken wrote:

> I managed to fix my problem, but I don't understand why the fix works
> yet, so I'm not quite satisfied.

[...] 

> class Block:
>     def __init__(self, name, preds = [], succs = []):

Heureka! Providing mutables as default values is a well-known pitfall. 

http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects

The default values are evaluated only once, so you end up sharing
predecessors and successors between all Block instances that are created
without explicitly passing preds and succs. A minimal example:

>>> def f(a, alist=[]):
...     alist.append(a)
...     print alist
...
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(3)
[1, 2, 3]

The standard workaround is to initialize the would-be list with None like
followed by a test in the function body:

>>> def f(a, alist=None):
...     if alist is None: alist = []
...     alist.append(a)
...     print alist
...
>>> f(1)
[1]
>>> f(2)
[2]
>>> alist = []
>>> f(1, alist)
[1]
>>> f(2, alist)
[1, 2]

Peter




More information about the Python-list mailing list