1

When I reading code MySQLdb, in times.py, i can not understand one line code:

return date(*localtime(ticks)[:3])

Any one can tell me what's use of '*', thanks a lot.

ericfang
  • 343
  • 2
  • 8

3 Answers3

4

It's known as the splat operator which turns a sequence into positional arguments to be used by that given function. There is also a double splat operator in case you didn't know which converts a dict to named arguments which are then passed to the function. Also read this for more relevant discussion.

As an example:

def printIt(*args, **kwargs):
  print 'Splat Contents=%s' % str(args)
  print 'Double Splat Contents=%s' % str(kwargs)

lst = [1, 2, 3]
dct = { 'name': 'sanjay', 'age': 666 }
printIt(*lst, **dct) # usage

So basically to conclude, splat when used in function application means "take this sequence, unpack it and pass it as positional arguments". splat when used in function definition means "this functions takes a variable number of positional arguments". Similar reasoning can be applied to the double splat operator. This is the reason the most generic function definition looks something like def funcName(*args, **kwargs) (as already posted in my example which can handle any sort of arguments).

Community
  • 1
  • 1
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • @glglgl: [Here](http://www.catb.org/jargon/html/S/splat.html) is one reference which can be found online. I always visualize this operator as a paint-ball hitting a solid wall which gives similar appearance. This terminology is pretty common in the Ruby community and this terminology is recently picked up by a lot of languages. Surely beats the 'unpacking arguments list' phrase I would say... ;) – Sanjay T. Sharma Apr 15 '13 at 07:56
  • That's not a useful description, though. "Splat operator" tells you nothing about what it actually does. "Unpacking operator" at least gives you an idea what it's about. You don't call a `+` a "cross operator" either, do you? Also, the Jargon File is a couple of decades old by now... – Tim Pietzcker Apr 15 '13 at 08:02
2

I will try to explain it by example. The following code

params = [1, 2, 3]
func(*params)

Is equivalent to this:

func(1, 2, 3)

So this basically allows you to call a function with parameters coming from a list. In you particular example there's a function call (which returns a list) and a list slicing added, but you should have figured that out.

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
0

It unpacks the first three elements of into localtime(ticks) and uses them as arguments for the date function.

jamylak
  • 128,818
  • 30
  • 231
  • 230