Issue
What is the difference between
i: int = 1
and
i = int(1)
Is the one better than the other?
Solution
Until you know that you need something else, just use i = 1
.
In Python, 1
and int(1)
return the same value (of type int
), and the latter does more work to do so, and thus is redundant, so just use 1
if you need the integer 1.
If you need a floating point value instead (for non-integer calculations in the future), use e.g. 1.0
(e.g. as f = 1.0
).
The difference between i = ...
and i: int = ...
is that the latter contains a type hint. The type hint states that the variable i
should contain values of type int
(e.g. 1
, 2
, but not 1.0
or '1'
). Type hints are ignored in many situations, so they don't make a difference. If you don't already have a compelling reason to use them, don't use them.
Here is how type hints are used as of Python 3.12:
- CPython (the default, official Python interpreter), as of version 3.12, ignores type hints: CPython executes the .py program as if type hints were removed.
- Numba, a Python JIT (for executing some Python code faster), ignores type hints on function arguments. It respects type info specified in Numba decorators instead.
- mypyc, a Python compiler (which compiles Python modules to C extensions, which run faster than the original Python modules) does use type hints. The more type hints the .py source files contain, the faster code mypyc generates.
- There are type checkers implemented as command-line tools (such as mypy) which read and analyze (but not execute) .py source code, and print type errors. For example, they report an error for
f: float = 1.0; i: int = f; print(i)
, but CPython still executes the code without an error. (Please note that mypy acceptsi: int = 1; f: float = i; print(f)
without an error, even thoughtype(f)
isint
, which is not (a subclass of)float
.) - There are some type checkers integrated to code editors (IDEs) such as PyCharm and Visual Studio Code. They run in the background and display type errors within the file editing window. Some type checkers (such as mypy above) can run both from the command-line and in a code editor.
Answered By - pts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.