davka
davka

Reputation: 14682

calling a list of functions in a particular order?

I'd rather do this

class A:
    def __init__(self):
        self._TESTS = {
            'val1': self.test1,
            #...
            'val10': self.test10
        }
    def test(self, x):
        for v, f in self._TESTS.items():
            if f(x):
                return v
        return None

over this

class A:
    def test(self, x):
        if self.test1(x):
            return 'val1'
        #...
        if self.test10(x):
            return 'val10'
        return None

However I need to call the test* methods in a particular order. How would you do this?

I could use collections.OrderedDict, but actually I don't a dictionary at all as I call all the test at once always. So, a list of tuples perhaps?

Upvotes: 1

Views: 52

Answers (4)

mzoll
mzoll

Reputation: 477

I do not quite understand the question as you already provide a possible answer which would quite certainly work. The full answer is: it depends. If it is important that you still keep your Test dictionary around, to have some kind of external access to it, then you should just specify the sequence of execution in your test(self, x) method:

class A:
def __init__(self):
    self._TESTS = {
        'val1': self.test1,
        #...
        'val10': self.test10
    }
def test(self, x):
    my_test_sequence = ['val10', 'val1']
    for v in my_test_sequence:
        if self._TESTS[v](x):
            return v
    return None
def test1(self, arg):
    return True
def test10(self, arg):
    return True

A().test(1) #val10

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

If your test functions placed in arbitrary order - use a sorted list of tuples:

class A:
    def __init__(self):
        self._TESTS = [
            (2, 'val10', self.test10),
            ...
            (1, 'val1', self.test1),
            #...                
        ]

    def test(self, x):
        for t in sorted(self._TESTS):
            if t[2](x):
                return t[1]
        return None

Upvotes: 1

zimmerrol
zimmerrol

Reputation: 4951

You could simply use a list of tuples, like this:

self._TESTS =[("v1", self.test1), ...]

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

yes, works with a list of tuples, order preserved, no need for dict since no need for lookup. The loop is just slightly different, no more .items() but direct unpacking:

class A:
    def __init__(self):
        self._TESTS = [
            ('val1', self.test1),
            #...
            ('val10', self.test10)
        ]
    def test(self, x):
        for v, f in self._TESTS:
            if f(x):
                return v
        return None

Upvotes: 2

Related Questions