ImportError: cannot import name 'inf'

ImportError: cannot import name 'inf'

我是 Python 的新人,我遇到了这个问题。当我 运行 我的脚本显示此错误时:

Traceback (most recent call last):
  File "./message", line 2, in <module>
    from src.graph_lib import *
  File "/export/home/xsymersk/TGR/src/graph_lib.py", line 2, in <module>
    from math import inf
ImportError: cannot import name 'inf'

我的代码有这个导入结构:

graph_lyb.py:

from src.dfs_lib import *
from math import inf
from collections import Counter
from operator import itemgetter

dfs_lib.py:

from enum import Enum

message.py:

from src.graph_lib import *
from sys import stdin

forest.py:

from src.graph_lib import *
from sys import stdin

race.py:

from src.graph_lib import *
from sys import stdin

代码 运行ning 没有 inf 导入。

您不必从数学模块导入 infmath.isinf 函数存在,但要定义无限值,您可以使用 float('inf').

您使用哪个 python 版本?

math 包中的 inf 常量在 Python 3.5

中实现

(相关link:https://docs.python.org/3/library/math.html#math.inf)

您应该检查您使用的 Python 版本。

如前所述,math.inf 是 python 3.5 的新增功能。 inf 一直存在,因为 float('inf')math.inf 实际上只是一种方便。如果您喜欢使用 math.inf,您可以将代码限制为受支持的版本

import sys
if sys.version_info < (3,5):
    raise ImportError('{} requires python version 3.5 or later'.format(__name__))

或者您可以自己添加

import sys
import math
if sys.version_info < (3,5):
    math.inf = float('inf')
    math.nan = float('nan')
    math.tau = math.pi * 2.