3 ms·
I've long wanted some kind of "null-filling" destructuring operator in Python, to avoid cases like this: # oops, ValueError on `item = "noequals"` key,
by woodruffw 5y ago
I've long wanted some kind of "null-filling" destructuring operator in Python, to avoid cases like this:
# oops, ValueError on `item = "noequals"`
key, value = item.split("=", 1)
That alone makes destructuring somewhat limited, unless I'm either willing to validate my lengths ahead of time or do exception-driven control flow. Something like `?=` perhaps, to complement the walrus operator.
- klyrs 5y agoDoes this work for you? key, *value = item.split("=", 1) if value: value = value[0] else: value = None
- woodruffw 5y agoYep, that's a pattern I've applied before. It's not the worst, but I don't think it has the clarity that this would have: key, value ?= item.split("=", 1) Modulo bike shedding over the actual syntax, of course. (Edit: the semantics of this could be even more generic, like Ruby's `[...] rescue value` syntax for turning any raised exception into a default value instead.)
- xtreak29 5y agoThere was a similar PEP https://peps.python.org/pep-0505/ https://peps.python.org/pep-0505/
- srfwx 5y agovalue = value[0] if value else None
- tech2 5y agoIs empty string acceptable in place of None? If so, consider partition: key, sep, value = item.partition("=") If you need to know whether there was a split/match that occurred you could test sep's truthiness.
- deleted 5y ago[deleted]