So basically, when i go to the builtins.py file, i find many functions like this:
def foo(o: object, arg: int | None = ...) -> int: ...
When i tried this out myself, it actually didn’t give out any errors, and still works like a normal function. I’m wondering why people use it and what the purpose of it is. When i make a function like the foo function (which is the first example given before this one):
def bar(arg: int, arg1: int | None = ...) -> int:
try:
return arg + arg1
except:
print('You cannot add a string and int together')
I don’t find any difference between def bar(arg: int, arg1: int): ... and def bar(arg: int, arg1: int | None = ...) -> int: ...
>Solution :
This is a type hint. In this case, int | None is a Union type indicating that the arg parameter will either be an int or None.
You might also find some valuable background info here: PEP 483.
One benefit of these hints is that IDEs and linters can use them to help analyze your code and catch certain kinds of errors. Some more high-level info is available here.