Domanda

I call a method of an external library multiple times in my class like this:

class MyClass:

    const_a = "a"
    const_b = True
    const_c = 1

    def push(self, pushee):
        with ExternalLibrary.open(self.const_a, self.const_b, self.const_c) as el:
            el.push(pushee)

    def pop(self):
        with ExternalLibrary.open(self.const_a, self.const_b, self.const_c) as el:
            return el.pop()

The lines containing the with statement are bugging me, because they require passing the the constants as arguments every time. I would like to store the arguments in a predefined data structure like a tuple and pass that to the external library.

È stato utile?

Soluzione

You can do this:

args = (const_a, const_b, const_c)
ExternalLibrary.open(*args)

The * syntax unpacks an iterable (tuple, list, etc.) into individual arguments in a function call. There is also a ** syntax for unpacking a dictionary into keyword arguments:

kwargs = {'foo': 1, 'bar': 2}
func(**kwargs) # same as func(foo=1, bar=2)

You can also use both in the same call, like func(*args, **kwargs).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top