Reputation: 405
I was coding on a project and at one moment I did the following code:
my_var = function(param)
my_var = my_var[key] if my_var else None
This code is working but I'm searching a better way to do it, in one line if possible.
Do you have any idea ?
In C# they is something called "Safe navigation operators" and you could have something looking like this I think:
my_var = function(param)?.[key]
Thanks for your answers !
Upvotes: 0
Views: 129
Reputation: 51
If function always returns a dictionary, you could do the following:
my_var = function(param).get(key, None)
Upvotes: 1
Reputation: 2325
The latest versions of Python, as of Oct 2018, do not support optionals.
For more details, see PEP505.
Upvotes: 1