pythonnonetype

Convert to int if not None, else keep None


I have a request dict and I need to parse some elements into either int or None. This works:

request = {"a": "123", "c": "456"}
a, b = request.get("a"), request.get("b")                       # too many 
a, b = int(a) if a is not None else None, int(b) if b is not None else None             # repetitions of "a" and "b" in this code!
print(a, b)  # 123 None

but I guess it might be simplified, ideally with a one-liner.

Is there a workaround, with standard built-in functions (and no extra helper util function) to be able to do a = int(request.get("a")) without int producing an error if the input is None?

Note: in this question I'm not really interested in the for loop part, what I'm interested in is how to simplify this:

a = request.get("a")
a = int(a) if a is not None else None

which I don't find pythonic.

Is there a way to simplify this pattern:

... if a is not None else None

?


Solution

  • ideally with a one-liner

    Avoid one-liners. Learn how a beautiful code looks like in Python. Avoid overusing the word "pythonic".

    request = {'a': '123', 'c': '456'}
    
    if 'a' in request:
        a = int(request['a'])
    else:
        a = None
    
    if 'b' in request:
        b = int(request['b'])
    else:
        b = None