Created
March 8, 2017 16:43
-
-
Save dberzano/3ddc21af95b906e91d58863b3550443d to your computer and use it in GitHub Desktop.
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
#!/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'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mconcas devil's in the detail