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.
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).
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.
It unpacks the first three elements of into localtime(ticks)
and uses them as arguments for the date function.