Skip to content

Instantly share code, notes, and snippets.

@PuercoPop
Created June 11, 2013 04:39
Show Gist options
  • Save PuercoPop/5754504 to your computer and use it in GitHub Desktop.
Save PuercoPop/5754504 to your computer and use it in GitHub Desktop.
Why it is important to use immutable as default arguments for function
# -*- 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