What does this PEP propose? Things like the followings wouldn’t throw you an exception anymore:
title ?? 'Default Title' title = user_title ?? local_default_title ?? global_default_title (requested_quantity ?? default_quantity) * price data = data ?? [] data ?= [] title?.upper() person?['name']
A new null coalescing operator since Python 3.6, the PEP currently is with draft status. Frankly, I love the idea of having this operator, Perl has it since 2009-08-23 for version 5.10 and the upcoming PHP 7. This operator must be very popular and demanding.
Although I sometimes feel annoying when I need to use the following somewhat lengthy conditional expression syntax, as known as ternary operator, especially you need to type title twice, but it’s Python and that’s Python.
title if title is None else 'Default Title'
However, I can still live with this, even I really do wish it can have some shortcut. Of course, you can use and and/or or, but it has its caveats if you ain’t careful, although in this case, it’s safe to be just1
title or 'Default Title'
As for this new possible operator, to me, the most helpful would be the Null-Aware Member Access Operator and Null-Aware Index Access Operator in the last two line of the first example.
The second case isn’t quite as needed for me. I don’t mind using
person.get('name', None)
But for the first case, I always can’t remember how to use hasattr, I know what I need to put in, just not the order. Which goes in first? Instance person or attribute name 'name'?
Even this operator would come in very handy, I am just not sure about the syntax. More precisely, the choice of ? character, which seems to be the universal choice among languages. Nonetheless, it just looks strange in Python and I don’t think it’s not out of line to say that
person?['name']
is not the Python I know. It’s easy to type, but it just doesn’t look Python. And for sake of arguments, what if, and it’s not far actuality, someone wants to use this operator like
company?['people']?['CEO']?['name']
[1] | Is it? Think about the case of '' and blank title is allowed. |
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.