Skip to main content

How to Allow None in a Python Type Hint

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A function sometimes gets a real value and sometimes None, such as an age that may be unknown. A type hint can say so: int | None means "an integer, or None". This guide writes such a function and calls it both ways, with real output from Python 3.15.2.

Syntax​

Syntax
def <function>(<parameter>: <type> | None) -> <return type>:
...
PartWhat it means
<type> | NoneThe value is either of <type> or None
-> <return type>The type the function returns. Hints can be written for both

The built-in types reference: "A union object holds the value of the | (bitwise or) operation on multiple type objects. These types are intended primarily for type annotations."

Prerequisites​

  • uv and Python 3.10 or newer. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

describe takes an age that may be None, and checks for None before using it.

optional_hint.py
def describe(age: int | None) -> str:
if age is None:
return "Age unknown"
return f"Age {age}"


print(describe(36))
print(describe(None))

The optional_hint.py script in a macOS-style code window: def describe(age: int | None) -> str, which returns Age unknown when age is None and Age with the number otherwise, then two print calls with 36 and None.

Step 2: Run It​

Terminal
uv run python optional_hint.py
Output
Age 36
Age unknown

The script's output in a terminal: Age 36, then Age unknown.

Both calls match the hint, and the None case has its own answer.

Common Mistakes​

MistakeWhat happensDo this instead
Writing int or NonePython evaluates it to just int: the stored hint was {'age': <class 'int'>, ...}int | None, stored as {'age': int | None, ...}
Expecting the hint to stop wrong valuesPython doesn't check hints when the program runs: describe("thirty-six") printed Age thirty-sixUse a type checker in your editor, or check the value in code

Troubleshooting​

SymptomLikely causeFix
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' inside the functionThe code used the value before checking for None: age + 1 with NoneCheck if age is None: first, as describe does

FAQ​

Is int | None the same as Optional[int]?​

Yes. The typing reference: "Optional[X] is equivalent to X | None (or Union[X, None])." int | None is the shorter form, built into the language.

Where can I see a function's hints?​

In its __annotations__: for describe it showed {'age': int | None, 'return': <class 'str'>}.

Conclusion​

age: int | None told readers and tools that describe accepts an integer or None, and the function answered Age 36 and Age unknown. Python stores the hint but doesn't enforce it.

Additional Resources​