ReduxDJ
ReduxDJ

Reputation: 479

Python, returning a tuple of tuples into locals inside a function

t = (('page',1),('count',25),('skip',0))

def get_arguments(t):
 page = 1
 count = 25
 skip = 0

Basically, what's best way to iterate over the tuple and set these arguments in my function like the example?

Upvotes: 0

Views: 154

Answers (5)

glglgl
glglgl

Reputation: 91017

tupleData = (('page',1),('count',25),('skip',0))

class DottedDict(dict):
    def __init__(self, *a, **k):
        super(DottedDict, self).__init__(*a, **k)
        self.__dict__ = self

def get_arguments(tupleArg):
   d = DottedDict(tupleArg)
   print d.page, d.count, d.skip

get_arguments(tupleData)

In principle, a normal dict would work as well if you do d['page'] etc. instead, but the dotted access is even shorter.

Upvotes: 0

Dseed
Dseed

Reputation: 172

You can do this:

page, count, skip = [t[1] for t in tuple]

Upvotes: 0

planestepper
planestepper

Reputation: 3297

You can also use **kwargs:

t = (('page',1),('count',25),('skip',0))
arguments = dict(t)

def get_arguments(page, count, skip):
    #page = 1
    #count = 25
    #skip = 0

#call your function with
get_arguments(**arguments)

And don't name the variable as tuple.

Upvotes: 4

Achim
Achim

Reputation: 15702

def get_arguments(page,count,skip):
     print page, count, skip

get_arguments(page=1, count=25, skip=0)

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239463

tupleData = (('page',1),('count',25),('skip',0))

def get_arguments(tupleArg):
   page, count, skip = zip(*tupleArg)[1]
   print page, count, skip

get_arguments(tupleData)

Output

1 25 0

Upvotes: 0

Related Questions