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: ...
CodePudding user response:
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.
CodePudding user response:
|
is the or
operator. So it's basically saying the type of arg1
can be either an integer or None.
See more here: https://docs.python.org/3/library/typing.html#typing.Optional
CodePudding user response:
it's a type hint or type annotation. it's described in PEP 484 and |
means union so basically arg1 can be int or NoneType. and why do we need to type hint? that's because it helps us to code more safely and in handy. if you use any decent IDE, you can get help of auto-completions by IDE thanks to its type hint.
CodePudding user response:
The -> int between the arguments list and the colon is the return type of that function. That allows you to specify what the function is going to return, so that if you have a larger function that spans the height of the screen, you don’t have to hunt through the function to find the returns and determine their types.
The | operator is a union, meaning that the function takes a parameter that is either one of the two types. For example, a function def func(param: int|str, param2: bool|float)
would take a param of either an int
or a str
, and param2 would be either a bool
or a float
Or, in the case of dictionaries, the | operator merges the two dictionaries together into one.