ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:\Anaconda\envs\tensorflow\lib\typing.py)

Time:2024-5-16

Reporting Errors Background:

I downgraded python 3.8 to 3.7 in my original newly created anaconda environment (mine is named tensorflow) because the tensorflow-gpu version needs to be installed.


The following error occurs when importing the seaborn package:

ImportError: cannot import name 'Literal' from 'typing' (D:\Anaconda\envs\tensorflow\lib\typing.py)

Cause analysis:

This is due to the fact that ‘Literal’ only supports python version 3.8 and above, and is not supported for python 3.7. If you don’t want to upgrade the python version (upgrading is a real pain in the ass and may cause my tensorflow-gpu version to not work anymore), see the solution below:


Situation one:

If you simply want to import a Literal:

First install typing_extensions in your environment (this is for python version 3.8 and below), the installation code is as follows:

pip install typing_extensions

Then you can import it using the following code sentence

from typing_extensions import Literal

Situation two:

If you are like me and want to import other packages (like seaborn), but encountered this error, here is the error and the solution:

The error is reported as follows:
ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:\Anaconda\envs\tensorflow\lib\typing.py)
Solution:
Find your corresponding path, open the .py file prompted with the red box (open it any way you want, I used pycharm to open it), find the corresponding location, and change it to the following:

from typing import (
    IO,
    TYPE_CHECKING,
    Any,
    AnyStr,
    Callable,
    Collection,
    Dict,
    Hashable,
    List,
    Mapping,
    Optional,
    Sequence,
    Tuple,
    Type as type_t,
    TypeVar,
    Union,
)
from typing_extensions import (
        Literal,
        TypedDict,
        final,
    )

ImportError: cannot import name ‘xxx’ from ‘typing’
I.e., go back to this .py file and make changes, such asTypedDict, You can’t put from typing import above, otherwise, it will report similar error.

After I modified the _typing.py file and ran it again, it reported the following error again (but at least it wasn’t the same error as before)

No module named 'pandas._libs.interval'

This error is good to correct, in your environment, install the following:

pip install --force-reinstall pandas

At this point, the problem is finally solved, and you can import seaborn.

Recommended Today

Unable to save ip settings, prompted to check one or more settings and try again.

Some users upgraded their computers to Win11 system, they want to set ip, but they found that they can’t save ip settings please check one or more settings and retry, how do we solve it? Pure Home – win7 pure version system_win7 ghost pure version cure 1, “win + R” shortcut key to open the […]