Why does split method behave differently in an inline if-else statement?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
MicroP_W691
Posts: 10
Joined: Mon Mar 09, 2020 10:47 am

Why does split method behave differently in an inline if-else statement?

Post by MicroP_W691 » Tue May 18, 2021 10:13 am

I'm a bit confused why the behaviour of the split statement is different between two use cases, and wondered what I may have overlooked?

This works the way I'd expect it to:

Code: Select all

>>> u = 'm/s^2'
>>> if '^' in u:
        a, b = u.split('^')
>>> a
'm/s'
>>> b
'2'
Now I tried to simplify this into a single statement, but instead got this behaviour:

Code: Select all

>>> u = 'm/s^2'
>>> a,b = u.split('^') if ('^' in u) else u,''
>>> a
['m/s', '2']
>>> b
''
What causes this difference?

MicroP_W691
Posts: 10
Joined: Mon Mar 09, 2020 10:47 am

Re: Why does split method behave differently in an inline if-else statement?

Post by MicroP_W691 » Tue May 18, 2021 10:26 am

Oops, I figured out the issue, user error! The object after the last comma is being assigned to the 'b' variable, which make sense based on how the line would tokenised and parsed by the interpreter.

The correct implementation should be:

Code: Select all

>>> a,b = u.split('^') if ('^' in u) else (u,'')
This returns a + b as expected.

SpotlightKid
Posts: 463
Joined: Wed Apr 08, 2015 5:19 am

Re: Why does split method behave differently in an inline if-else statement?

Post by SpotlightKid » Tue May 18, 2021 10:29 am

You are missing some parentheses (and have others, which are not necessary).

Correct:

Code: Select all

a, b = u.split('^') if '^' in u else (u,'')
Your original code gets parsed like this:

Code: Select all

a, b = (<ternary-expression>, '')
And then tuple unpacking and assignment assigns the result of the ternary expression (the first element of the tuple) to a and the empty string (the second element) to b.

Lesson: commas are very important in Python :)

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Why does split method behave differently in an inline if-else statement?

Post by pythoncoder » Tue May 18, 2021 10:50 am

This is a common "gotcha" and it's down to the way Python parses the code. It is effectively executed as

Code: Select all

a,b = (u.split('^') if ('^' in u) else u),''
rather than

Code: Select all

a,b = u.split('^') if ('^' in u) else (u,'')
Peter Hinch
Index to my micropython libraries.

MicroP_W691
Posts: 10
Joined: Mon Mar 09, 2020 10:47 am

Re: Why does split method behave differently in an inline if-else statement?

Post by MicroP_W691 » Tue May 18, 2021 3:27 pm

Thanks guys :)

Post Reply