Why does Python log a warning for “invalid decimal literal”?2021-09-16
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
def get_level(is_high: bool) -> int: return 100 if is_high else 0
Now Python can run the code without warning.
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.
- “invalid octal literal”: e.g.
- “invalid imaginary literal”: e.g
If your Django project’s long test runs bore you, my book can help.
One summary email a week, no spam, I pinky promise.
- Why does Python log a SyntaxWarning for ‘is’ with literals?
- Why does Python log a SyntaxWarning saying “object is not subscriptable”?
- Why does Python log a SyntaxWarning saying “assertion is always true”?
- Why does Python log a SyntaxWarning saying “object is not callable”?
© 2021 All rights reserved.