How to expand the tuple in profitability?

I am trying to extend a tuple in a yield statement, but I am getting SyntaxError. Is this possible, or is it an operator *only for function calls?

The following is an example:

class Inner(object):
    def __init__(self):
        self._vals = {'a': 1,
                      'b': 2,
                      'c': 3,
                      'd': 4}

    def __iter__(self):
        for key, val in self._vals.items():
            yield key, val

class Outer(object):
    def __init__(self):
        self._morevals = {"foo": Inner(),
                          "bar": Inner()}

    def __iter__(self):
        for key, moreval in self._morevals.items():
            for val in moreval:
                yield key, *val    # !!! <--- This is where the error is

object_under_test = Outer()

for outer_key, inner_key, inner_value in object_under_test:
    print("{} {} {}".format(outer_key, inner_key, inner_value))

    # Want:
    # foo a 1
    # foo b 2
    # foo c 3
    # foo d 4
    # bar a 1
    # bar b 2
    # bar c 3
    # bar d 4

Instead, I get this error:

    yield key, *val
               ^
SyntaxError: invalid syntax
+4
source share
2 answers

Add parentheses either around the tuple:

yield (key, *val)

yieldthis is a special feature, since a form accepts only a list of expressions, not a starred_listform .

+8
source

You need to copy it in brackets. In short, use:

yield (key, *val)

, yield from . , __iter__ :

 def __iter__(self):
    items = self._morevals.items()
    yield from ((k, *v) for k, vals in items for v in vals)

, yield from ClassOne.__iter__:

def __iter__(self):
    yield from self._vals.items()
+5

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


All Articles