Search code examples
python-3.xconstantsfinaltypingpython-3.8

Declaring a constant variable in Python 3.8 triggers "Module 'typing' has no attribute 'Final'" error/warning (Python 3.8, Thonny IDE)


I'm trying to declare constants in Python 3.8 with the following code:

from typing import Final

It is a new feture in Python 3.8. See https://docs.python.org/3/library/typing.html for details. Thonny IDE's bundled interpreter (3.7) gives an error:

Traceback (most recent call last): File ".../decimal_arithmetics.py", line 2, in from typing import Final ImportError: cannot import name 'Final' from 'typing' (/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py)

It is understandable, while it is a new feature in version 3.8 and Thonny still uses version 3.7.

However, with the interpreter changed in preferences to a separately installed Python 3.8 one, I still have an IDE warning:

Line 2 : Module 'typing' has no attribute 'Final'

What is the cause of this warning?

Please, let me know if some other information is necessary to clarify the question.


Solution

  • Explanation

    Thonny's assistant uses Pylint and Mypy in order to provide the warnings. Pylint is mostly used for checking if the code is using proper Python coding standards (PEP8), while Mypy is used for checking static types for Python. In this case, the warning "Module 'typing' has no attribute 'Final'" is coming from Mypy.

    Now, why does Mypy show that warning when Final does exist within typing on your interpreter? It's showing the warning because it's not checking your interpreter's typing.py, it's checking Thonny interpreter's typing.py. It doesn't matter that you've set it to use your own interpreter over Thonny's, the assistant always checks your code as if you were using Thonny's interpreter.

    Solution

    There are a couple ways you could stop the warning from appearing:

    1. you could replace Thonny interpreter's typing.py with your interpreter's typing.py, but this is risky as it may lead to unexpected behavior if you ever decide to use Thonny's interpreter;

    2. you could turn off Mypy checks for the assistant. You can do this by going to: Tools->Options...->Assistant and then uncheck Perform MyPy checks.