reorx
12/13/2012 - 10:06 AM

tricky and noteworthy arguments passing ways in python

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