[Tutor] Playing with generators

Mats Wichmann mats at wichmann.us
Wed Aug 10 19:15:36 EDT 2022


On 8/10/22 15:00, Leam Hall wrote:

oops, skated right by this question:

> On 8/10/22 12:12, Mats Wichmann wrote:
>> On 8/10/22 05:32, Leam Hall wrote:
> 
>>> class Person():
>>>      def __init__(self, data = {}):
>>
>> don't do this: don't use a mutable default argument
> 
> Hey Mats, can you explain why that's an issue? In this case, data is the
> dict of key word arguments, when the number of kwargs will be long.

There's nothing wrong with using a dict parameter.  Defaulting the
parameter to an empty dict is *potentially* a problem - Python evaluates
that only once, when the function definition is first worked up, and
makes an entry in the function object created - meaning every call to
the function will share the same object, which can change over time if
it's a mutable object, like a dict, list, etc..  In your toy example,
you don't change it in the function, only read it, so that won't break,
but code checkers, IDEs, etc. will nonetheless complain - they have no
way to know for sure you might not later change your mind and modify the
object in the function, at which point things will for sure break.

Interestingly, when you get around to studying dataclasses, they work
around that oh-so-common problem (it makes basically every list of
"Common Python surprises and pitfalls") with some extra boilerplate - it
will insert a call to a factory function to get you the type you want,
so it becomes per-instance rather than only-one - but as you've
indicated, that's an issue for another day!!!



More information about the Tutor mailing list