Bolster
Bolster

Reputation: 7906

Python, tuple arguments playing nicely with others

For example:

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

printstuff(mytuple," How are you")

This naturally crashes out with a TypeError because I'm only giving it two arguments when it expects three.

Is there a simple way of effectively 'splitting' a tuple in a tider way than expanding everything? Like:

printstuff(mytuple[0],mytuple[1]," How are you")

Upvotes: 4

Views: 3057

Answers (6)

Nuageux
Nuageux

Reputation: 1686

Actually, it is possible to do it without changing the order of the arguments. First you have to transform your string to a tuple, add it to your tuple mytuple and then pass your larger tuple as argument.

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

Upvotes: 0

Derek Litz
Derek Litz

Reputation: 10897

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

Upvotes: 1

Skurmedel
Skurmedel

Reputation: 22149

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 pretty much as long as you qualify any argument coming after it with its name.

Upvotes: 6

S.Lott
S.Lott

Reputation: 391846

Not without changing the argument ordering or switching to named parameters.

Here's the named parameters alternative.

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

Here's the switch-the-order alternative.

def printstuff( three, one, two ):
    print one, two, three

printstuff( " How are you", *mytuple )

Which may be pretty terrible.

Upvotes: 4

rlotun
rlotun

Reputation: 8063

You could try:

def printstuff(*args):
    print args

Another option is to use the new namedtuple collections type.

Upvotes: 0

yan
yan

Reputation: 20982

Try the following:

printstuff(*(mytuple[0:2]+(" how are you",)))

Upvotes: 3

Related Questions