Python, tuple arguments playing nicely with others

For instance:

mytuple = ("Hello","World") def printstuff(one,two,three): print one,two,three printstuff(mytuple," How are you") 

This naturally flies out with TypeError, because I give it two arguments when it expects three.

Is there a simple way to effectively "split" a tuple in a secret way than expanding everything? How:

 printstuff(mytuple[0],mytuple[1]," How are you") 
+4
source share
6 answers

Without changing the order of the arguments or switching to named parameters.

Named parameters are listed here.

 printstuff( *mytuple, three=" How are you" ) 

Here's an alternative to the select-switch.

 def printstuff( three, one, two ): print one, two, three printstuff( " How are you", *mytuple ) 

Which can be pretty awful.

+4
source

Kinda ... you can do this:

 >>> def fun(a, b, c): ... print(a, b, c) ... >>> fun(*(1, 2), 3) File "<stdin>", line 1 SyntaxError: only named arguments may follow *expression >>> fun(*(1, 2), c=3) 1 2 3 

As you can see, you can do what you want as long as you qualify any argument following it with his name.

+6
source

Try the following:

 printstuff(*(mytuple[0:2]+(" how are you",))) 
+3
source
 mytuple = ("Hello","World") def targs(tuple, *args): return tuple + args def printstuff(one,two,three): print one,two,three printstuff(*targs(mytuple, " How are you")) Hello World How are you 
+1
source

You can try:

 def printstuff(*args): print args 

Another option is to use the new namedtuple collection type .

0
source

Actually, this can be done without changing the order of the arguments. First you need to convert the string to a tuple, add it to your mytuple tuple, and then pass your big tuple as an argument.

 printstuff(*(mytuple+(" How are you",))) # With your example, it returns: "Hello World How are you" 
0
source

Source: https://habr.com/ru/post/1345615/


All Articles