Weird side effect of default parameter

Gary Herron gherron at digipen.edu
Thu May 3 16:14:55 EDT 2018


This is a well known feature of Python.   It's a very common "gotcha" to 
new Python programmers.

Google "Mutable default parameters in Python" for long list of 
explanations and fixes.

In short, don't use a mutable object as a default parameter.


Gary Herron



On 05/03/2018 12:47 PM, python-list at python.org wrote:
> Hello,
>
> I don't understand the behavior of the code below. Why does the dict property
> "a" of both objects contain the same keys? This is only if "a=dict" is in
> the initializer. If I put self.a = dict() into the init function, I get two
> separate dicts
>
>
>
> class Foo(object):
>      def __init__(self, x, a=dict()):
>          self.x = x
>          self.a = a
>          self.a[x] = x
>
>
> c = Foo(1)
> d = Foo(2)
>
> print(c.__dict__)
> print(d.__dict__)
>
>
> robert

-- 
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list