Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some Python functions have an extra set of parenthesis around the argument list?

I've seen some Python functions written like this:

def get_year((year,prefix,index,suffix)):
  return year

How does that differ (if at all) from other functions without the extra parentheses like this:

def do_format(yr,pfx,id,sfx):
  return "%s %s %s/%s"%(yr, id, pfx, sfx)

Or is it just a matter of taste in styles, or if they differ, can get_year() be rewritten to be in the style of do_format() or vice-versa without effecting existing caller's syntax?

like image 897
WilliamKF Avatar asked Feb 14 '13 17:02

WilliamKF


1 Answers

The first function takes a single tuple argument, whereas the second function takes 4 arguments. You can pass those parameters individually, or as a tuple with splat operator, that will unpack the tuple into individual parameters.

E.g:

# Valid Invocations
print do_format(*('2001', '234', '12', '123'))  # Tuple Unpacking
print do_format('2001', '234', '12', '123')     # Separate Parameter
print get_year(('2001', '234', '12', '123'))

# Invalid invocation. 
print do_format(('2001', '234', '12', '123'))   # Passes tuple
like image 192
Rohit Jain Avatar answered Nov 15 '22 12:11

Rohit Jain