jjacobi
jjacobi

Reputation: 405

Most pythonic way to assign and access a nullable object

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

Answers (2)

bigelbow
bigelbow

Reputation: 51

If function always returns a dictionary, you could do the following:

my_var = function(param).get(key, None)

Upvotes: 1

Sean Pianka
Sean Pianka

Reputation: 2325

The latest versions of Python, as of Oct 2018, do not support optionals.

For more details, see PEP505.

Upvotes: 1

Related Questions