Using default None values in Python when assigning split() to a tuple Let's say I want to parse audio track information into two variables like this:


'2/15' -> track = 2, num_tracks = 15
'7' -> track = 7, num_tracks = None


What's an elegant way to do this in Python? For example:

track, num_tracks = track_info.split('/')


This works for the first format, but not for the second, raising ValueError: need more than 1 value to unpack. So I came up with this:

try:
    track, num_tracks = track_info.split('/', 1)
except:
    track, num_tracks = track_info, None


How can this be more elegant or better?
try:
    track, num_tracks = track_info.split('/', 1)
except:
    track, num_tracks = track_info, None



Honestly, this is not a terrible solution. But you should almost never use except:; you should catch a specific exception.

Here is another way:

tracks, _, num_tracks = text.partition('/')
return int(tracks), int(num_tracks) if num_tracks else None