Skip to content

Instantly share code, notes, and snippets.

@idan
Created April 17, 2012 05:20
Show Gist options
  • Select an option

  • Save idan/2403662 to your computer and use it in GitHub Desktop.

Select an option

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

dstufft commented Apr 17, 2012

Copy link
Copy Markdown

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

idan commented Apr 17, 2012

Copy link
Copy Markdown
Author

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

Also, I'm retarded.

@chrisdev

Copy link
Copy Markdown

i think

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

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

@dcramer

dcramer commented Apr 17, 2012

Copy link
Copy Markdown

You should do what @dstufft recommends :)

@tebeka

tebeka commented Apr 17, 2012

Copy link
Copy Markdown

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

dcramer commented Apr 17, 2012

Copy link
Copy Markdown

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

@tebeka

tebeka commented Apr 17, 2012

Copy link
Copy Markdown

@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