Skip to content

Instantly share code, notes, and snippets.

@idan
Created April 17, 2012 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save idan/2403662 to your computer and use it in GitHub Desktop.
Save idan/2403662 to your computer and use it in GitHub Desktop.
Parameter Usage Style
# Which of these
def __init__(self, uri, http_method=u'GET', body={}, headers={}):
# do stuff with body and headers directly
headers['Content-Type'] = u'x-www-url-formencoded'
# etc...
# VERSUS #
def __init__(self, uri, http_method=u'GET', body=None, headers=None):
body = body or {}
headers = headers or {}
@dstufft
Copy link

dstufft commented Apr 17, 2012

I always prefer:

def __init__(self, uri, http_method="GET", body=None, headers=None):
     if body is None:
        body = {}

    if headers is None:
        headers = {}

But It's kinda verbose.

@idan
Copy link
Author

idan commented Apr 17, 2012

Apparently, the former is super-dangerous because dicts are mutable. (See: https://gist.github.com/2403699)

Also, I'm retarded.

@chrisdev
Copy link

i think

 def __init__(self, uri, http_method="GET", body=None, headers=None): 

is preferred see http://effbot.org/zone/default-values.htm

@dcramer
Copy link

dcramer commented Apr 17, 2012

You should do what @dstufft recommends :)

@tebeka
Copy link

tebeka commented Apr 17, 2012

I prefer the shorter version of @dstufft

def __init__(self, uri, http_method="GET", body=None, headers=None):
    body = body or {}
    headers = headers or {}

@dcramer
Copy link

dcramer commented Apr 17, 2012

@tebeka it might be simpler, but its useless extra cost, and is implicit behavior of overwriting the structure that you passed in

@tebeka
Copy link

tebeka commented Apr 17, 2012

@dcramer I don't follow. If you passed an empty structure, then a new empty one will be created which is not a big issue. The idea is not to mutate default arguments.
If you really care, you can probably use body = {} if body is None else body if you want to check for None explicitly.

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