Pythonic way of handling typing Optional?

Question:

I’m parsing dict coming from elsewhere and the value is optional

a: typing.Optional = elsewhere_dict.get(a)

When I want to run any 3d party functions on it, I call
b = foo(a) if a is not None else None
and I cant pass None to foo or wrap foo.
Is there a better way to call this, without repeating if a is not None else None?
Smth like b = call_optional(a, foo) but built-in or from std lib?

Asked By: Vitalii Ivanov

||

Answers:

I don’t think there is anything built-in for that, but it is rather trivial to implement call_optional yourself:

def call_optional(arg, func):
    if arg is not None:
        return func(arg)
Answered By: blhsing
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.