Skip to content

Instantly share code, notes, and snippets.

@reorx
Created December 13, 2012 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reorx/4275442 to your computer and use it in GitHub Desktop.
Save reorx/4275442 to your computer and use it in GitHub Desktop.
tricky and noteworthy arguments passing ways in python
# 1. multable keyword-argument won't be initialized each time function is called,
# it is created and stored at the time the function is defined.
# example: list
def pri(a=[]):
a.append(1)
print a
pri()
pri()
# example: dict
def pri(b, a={}):
a[b] = 1
print a
pri('x')
pri('y')
# example: dict created by function
def new_dict():
print 'create dict'
return dict()
def pri(b, a=new_dict()):
a[b] = 1
print a
pri('x')
pri('y')
# 2. dict type function is just a shallow copy
d = {
'a': [],
'b': 1
}
c = dict(d)
c['b'] = 2
print d, c
c['a'].append(1)
print d, c
# 3. change on keyword-argument may cause change on passing dict
def pri(**kwgs):
kwgs['a'].append(1)
d = {'a': []}
pri(**d)
print d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment