[英]ImportError: cannot import name 'Literal' from 'typing'
I have recently started using PEP 484 and PEP 586 to make my code clearer and more accessible.我最近开始使用PEP 484和PEP 586来使我的代码更清晰、更易于访问。 So far everything was ok, but when I wanted to use Literal
from the package typing
it appears it couldn't be imported.到目前为止一切正常,但是当我想使用 package typing
的Literal
时,它似乎无法导入。 What is the most surprising is that PyCharm isn't complaining at all for importing it or using it.最令人惊讶的是 PyCharm 根本没有抱怨导入或使用它。
The code I want to use in the end is looking like that:我最终想要使用的代码看起来像这样:
SomeVar = TypeVar("SomeVar", Literal['choice1'], Literal['choice2'], someType)
It would be used in the cases where you can have a string to describe what you want or an already made solution eg:在您可以使用字符串来描述您想要的内容或已经制定的解决方案的情况下,它会被使用,例如:
def someFunc(my_var: SomeVar = 'choice1'):
result = []
if my_var == 'choice1':
result.append(...)
else:
result = my_var
return result
I use an Anaconda environment with Python 3.7.7.我使用 Anaconda 环境和 Python 3.7.7。
Literal
in Python 3.8 and later在 Python 3.8 及更高版本中使用Literal
from typing import Literal
Literal
in all Python versions (1)在所有Python版本中使用Literal
(一) Literal
was added to typing.py
in 3.8, but you can use Literal
in older versions anyway. Literal
在 3.8 中被添加到typing.py
中,但您仍然可以在旧版本中使用Literal
。
First install typing_extensions
( pip install typing_extensions
) and then首先安装typing_extensions
( pip install typing_extensions
) 然后
from typing_extensions import Literal
This approach is supposed to work also in Python 3.8 and later.这种方法应该也适用于 Python 3.8 及更高版本。
Literal
in all Python versions (2)在所有 Python 版本中使用Literal
(2) For completeness, I'm also adding the try-except approach to import Literal
:为了完整起见,我还添加了 try-except 方法来导入Literal
:
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
This should also work for all Python versions, given that typing_extensions
is installed if you're using Python 3.7 or older.如果您使用的是 Python 3.7 或更早版本,假设已安装typing_extensions
,这也适用于所有 Python 版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.