Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Why does my Python function remember names from an earlier call?

Technology category photographTechnology

My practice function starts with `def add_name(name, names=[]):`, appends the name and returns the list. Calling it once for a new group works. Calling it again without passing a list brings back the earlier group's name too.

I thought the empty-list default meant “start a new list for this call”. Python's tutorial says default values are evaluated once and illustrates how a mutable default can be shared across calls. Python's default-argument explanation

How should I give separate groups fresh lists while still allowing a caller to supply a list intentionally? I don't want to clear a list someone passed in just to hide the unexpected carry-over.

Discussion

5 community replies

The default list is created when the function is defined, rather than afresh for each omitted argument. Appending changes that same list, so later calls using the default can see the earlier additions. That's the behaviour the tutorial warns about.

Use a sentinel default such as None, then create a new empty list inside the function only when the argument is None. Python's tutorial shows that pattern. A caller who supplies a list can still have that list used deliberately.

Don't solve the symptom by clearing the supplied list at the start. That would discard input from a caller who intentionally wants to add a name to an existing group. Your two use cases deserve different treatment.

Check two calls that omit the list and one that supplies an existing list. The omitted calls should start independently; the explicit-list call should follow the behaviour you've promised for that list.

Make the promised behaviour clear too: does adding a name modify the supplied list, or return a separate result? The fresh-default fix doesn't choose that design for you. Pick one and make the explicit-list example demonstrate it.

Join the discussion

More in Technology