-
-
Save bitprophet/2403699 to your computer and use it in GitHub Desktop.
Parameter Usage Style
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
>>> 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'} | |
>>> |
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
>>> 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'} | |
>>> |
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
>>> 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'} | |
>>> |
@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
Trivial nitpick: line 2 of good.py will change any falsey value to an empty dict. In most cases that's OK, but it's a bit safer to say
if headers is None: headers={}
explicitly. It's more wordy to be sure, but people tripped up by the "non-local dict kwarg" ought to be made aware of this, too.