Why does Python log a warning for “invalid decimal literal”?

Take this function:
def get_level(is_high: bool) -> int:
return 100if is_high else 0
If we run this with Python 3.10 in development mode (to enable deprecation warnings), we will see:
$ python3.10 -X dev example.py
/.../example.py:2: DeprecationWarning: invalid decimal literal
return 100if is_high else 0
(On Python 3.11 we would instead get a SyntaxWarning at import time, even without development mode.)
This is a new warning added in Python 3.10. As the release notes reveal, Python now warns for with numbers followed immediately by a keyword, without a space. This syntax is ambiguous, so Python is phasing it out.
The solution is is to add a space after 100:
def get_level(is_high: bool) -> int:
return 100 if is_high else 0
Now Python can run the code without warning.
Other Types
You can also see similar warning messages when using other kinds of numeric literals. In all cases the solution is to add a space:
- “invalid binary literal”: e.g.
0b100if→0b100 if - “invalid octal literal”: e.g.
0x100if→0x100 if - “invalid imaginary literal”: e.g
4jif→4j if
😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts:
- Python: fix
SyntaxWarning: "is" with a literal - Python: fix
SyntaxWarning: '<type>' object is not subscriptable - Python: fix
SyntaxWarning: assertion is always true - Python: fix
SyntaxWarning: '<type>' object is not callable
Tags: python