8

I can do an assignment destructuring as:

a, b = s.split(' ', 1)

for a string s which has more than one word.

How can we do the same in, say an if or elif, with the latest assignment expression introduced in Python 3.8 (is it possible to have multiple targets) ?

I tried:

if some_thing:
    # some code.
elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
    # some code probably using a and b as well.

I get following error:

elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
NameError: name 'a' is not defined

The reason I want this is because I don't want to split my string unnecessarily if my first condition is satisfied.

Austin
  • 24,608
  • 4
  • 20
  • 43
  • I just tried doing 'elif ((a,b) := ..... and got SyntaxError: cannot use named assignment with tuple So I don't think it's possible to do what you want. saying a, b = s.split() is implicitly working with tuples. – Neil Dec 07 '19 at 12:45

2 Answers2

4

See comment on question re assigning to a tuple. I'm by no means an expert though. Posting the below because it works and I think it may be good enough for you? Basically, save the tuple to one variable, which works, and then you can index it

if some_thing:
    # some code.
elif (split := s.split(' ', 1)):
    if some_func(split[0]) and some_func(split[1]):
        # some code probably using a and b as well.
Neil
  • 2,116
  • 2
  • 12
  • 28
  • 2
    Thanks for the answer. I know it works for a normal assignment; was keen on how the destructuring can be done. But I guess you're right that we can't do it in the way I did. Btw you could couple both `elif` and the `if` below together with an `and`. – Austin Dec 07 '19 at 14:02
0

If you try it with parentheses around your assigned-to tuple, the error message is way clearer and tells you something about the problem:

if ((a, b) := s.split(' ', 1)):
  ...

This will result in a SyntaxError: cannot use assignment expressions with tuple. And that's the whole point: Currently the walrus operator doesn't allow unpacking assignment. I also have no information about whether this is planned for the future or not. (Maybe there is even a logical reason I couldn't figure out why this isn't possible at all.) Given that they stripped the unpacking feature in parameter lists of functions (when moving from Python2 to Python3), I wouldn't expect it.

So all you can do here is the workaround of assigning to a single variable and indexing this later on.

Alfe
  • 47,603
  • 17
  • 84
  • 139