Skip to content

Instantly share code, notes, and snippets.

@bitprophet
Forked from idan/gist:2403662
Created April 17, 2012 05:26
Show Gist options
  • Save bitprophet/2403699 to your computer and use it in GitHub Desktop.
Save bitprophet/2403699 to your computer and use it in GitHub Desktop.
Parameter Usage Style
>>> def init(headers={}):
... print "headers before: %r" % headers
... headers['foo'] = 'bar'
... print "headers after: %r" % headers
...
...
>>> init()
headers before: {}
headers after: {'foo': 'bar'}
>>> init()
headers before: {'foo': 'bar'}
headers after: {'foo': 'bar'}
>>>
>>> mydict = {}
>>> def init(headers=mydict):
... print "before: %r" % headers
... headers['foo'] = 'bar'
... print "after: %r" % headers
...
...
>>> print mydict
{}
>>> init()
before: {}
after: {'foo': 'bar'}
>>> print mydict
{'foo': 'bar'}
>>>
>>> def init(headers=None):
... headers = headers or {}
... print "before: %r" % headers
... headers['foo'] = 'bar'
... print "after: %r" % headers
...
...
>>> init()
before: {}
after: {'foo': 'bar'}
>>> init()
before: {}
after: {'foo': 'bar'}
>>>
@bitprophet
Copy link
Author

@donspaulding Yes, that's always a potential gotcha, though in this case I felt it was worth using for example clarity, and because the kwarg is intended to be a dict -- another type of empty value is likely to be wrong anyways, and an empty dict would evaluate to the amusing but harmless expression {} or {}.

(You could argue that in a case where somebody gave e.g. 0 to a kwarg expecting a dict, we'd want it to ValueError or similar instead of silently casting to empty-dict, but I'm not sure that eventuality is worth changing things up for. Maybe use headers = {} if headers is None else headers, or just a two line `if block. A bit more verbose but also more correct.

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