Skip to content

Instantly share code, notes, and snippets.

@dberzano
Created March 8, 2017 16:43
Show Gist options
  • Save dberzano/3ddc21af95b906e91d58863b3550443d to your computer and use it in GitHub Desktop.
Save dberzano/3ddc21af95b906e91d58863b3550443d to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from __future__ import print_function
def disaster_function(a_default=[]):
# BEWARE: the next line, if a_default is not provided, modifies the default
# object, and **not a copy** of the default object! This is because you are
# modifying in place a "name" pointing to the default, by effectively changing
# the default value for all future function calls
a_default.append("a string")
print("disaster_function(): %s" % a_default)
def prevent_disaster(a_default=None):
# Prevent the disaster by setting defaults to None, and using it as a
# placeholder to trigger the creation to a unique, per-function call copy of
# the intended default
if a_default is None:
a_default = []
a_default.append("a string")
print("prevent_disaster(): %s" % a_default)
disaster_function() # expect: ['a string']
disaster_function() # naively expecting: ['a string'], getting ['a string', 'a string']
prevent_disaster() # expect: ['a string']
prevent_disaster() # getting as naively expected: ['a string']
@dberzano
Copy link
Author

dberzano commented Mar 8, 2017

@mconcas devil's in the detail

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment