Created
June 11, 2013 04:39
-
-
Save PuercoPop/5754504 to your computer and use it in GitHub Desktop.
Why it is important to use immutable as default arguments for function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""A short example of why you shouldn't use lists or dicts as default. In python | |
default parameteres are bounded when the function definition is executed as | |
part of module loading. So after the function is created the default arguments | |
always point the same object (being list or dict, list in this case.). One | |
should only use inmutable objects as None or strings as default arguments. | |
""" | |
def foo(bar=[]): | |
"""Never do this | |
""" | |
print bar | |
bar.append('fubar') | |
foo() | |
foo() # Oh noes situation fubar | |
def fixdfoo(bar=None): | |
if bar is None: | |
bar = [] | |
print bar | |
bar.append('fubar') | |
fixdfoo() | |
fixdfoo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment