Monday 20 November 2017

What does asterisk * mean in Python?





Does * have a special meaning in Python as it does in C? I saw a
function like this in the Python
Cookbook:



def get(self, *a,
**kw)


Would you please
explain it to me or point out where I can find an answer (Google interprets the * as
wild card character and thus I cannot find a satisfactory answer).



Answer





See href="https://docs.python.org/2.7/reference/compound_stmts.html#function-definitions"
rel="noreferrer">Function Definitions in the Language
Reference.




If the
form *identifier is
present, it is initialized to a
tuple
receiving any excess positional
parameters, defaulting to
the empty
tuple. If the form **identifier
is
present, it is initialized to a new
dictionary receiving any
excess

keyword arguments, defaulting to a new
empty
dictionary.




Also,
see rel="noreferrer">Function
Calls
.



Assuming that one knows what
positional and keyword arguments are, here are some
examples:



Example
1:




# Excess keyword
argument (python 2) example:
def foo(a, b, c, **args):
print "a =
%s" % (a,)
print "b = %s" % (b,)
print "c = %s" % (c,)

print args

foo(a="testa", d="excess", c="testc", b="testb",
k="another_excess")



As
you can see in the above example, we only have parameters a, b,
c
in the signature of the foo function. Since
d and k are not present, they are put
into the args dictionary. The output of the program
is:



a = testa
b =
testb
c = testc
{'k': 'another_excess', 'd':
'excess'}


Example
2:




# Excess positional
argument (python 2) example:
def foo(a, b, c, *args):
print "a =
%s" % (a,)
print "b = %s" % (b,)
print "c = %s" % (c,)

print args

foo("testa", "testb", "testc", "excess",
"another_excess")



Here,
since we're testing positional arguments, the excess ones have to be on the end, and
*args packs them into a tuple, so the output of this program
is:



a = testa
b =
testb
c = testc
('excess',
'another_excess')


You
can also unpack a dictionary or a tuple into arguments of a
function:




def
foo(a,b,c,**args):
print "a=%s" % (a,)
print "b=%s" %
(b,)
print "c=%s" % (c,)
print "args=%s" %
(args,)

argdict = dict(a="testa", b="testb", c="testc",
excessarg="string")
foo(**argdict)



Prints:



a=testa
b=testb
c=testc
args={'excessarg':
'string'}


And




def
foo(a,b,c,*args):
print "a=%s" % (a,)
print "b=%s" %
(b,)
print "c=%s" % (c,)
print "args=%s" %
(args,)

argtuple =
("testa","testb","testc","excess")
foo(*argtuple)



Prints:



a=testa
b=testb
c=testc
args=('excess',)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...