python中的相对导入和绝对导入的常见问题和解决方案

绝对导入

直接从当前模块进行导入包

# 下面是导入的自己写的类
from spatial_func import distance, SPoint
from mbr import MBR
from map_matching.candidate_point import CandidatePoint
from spatial_func import cal_loc_along_line

相对导入

主要是使用.或…等进行目录的锁定

from .spatial_func import distance, SPoint
from .mbr import MBR
from ..map_matching.candidate_point import CandidatePoint
from .spatial_func import cal_loc_along_line

报错源码

G:\githubuse\DeepMG-nbhd_dist>python tptk/main.py --phase 1 --conf_path ./data/conf_tdrive_sample.json --results_path ./data/tdrive_sample/results/
Traceback (most recent call last):
  File "tptk/main.py", line 3, in <module>
    from common.trajectory import Trajectory, store_traj_file, parse_traj_file
  File "G:\githubuse\DeepMG-nbhd_dist\tptk\common\trajectory.py", line 4, in <module>
    from ..map_matching.candidate_point import CandidatePoint
ValueError: attempted relative import beyond top-level package

类似报错

ValueError: attempted relative import beyond top-level package
# 翻译:试图在顶级包之外进行相对导入
ImportError: attempted relative import with no known parent package
# 翻译:尝试相对导入,但没有已知的父包
ValueError: Attempted relative import in non-package
# 翻译:试图在非包中进行相对导入
SystemError: Parent module '' not loaded, cannot perform relative import
# 翻译:父模块'xxx'未加载,不能执行相对导入。

解决方法

最简单的是将当前模块设置为root,然后在该模块中使用绝对导入。
如下,我将tptk设置为Sources Root。
在这里插入图片描述
在其中某个文件中的引用,其中的map_matching和common均为tptk模块的第一层子目录

from map_matching.hmm.hmm_probabilities import HMMProbabilities
from map_matching.hmm.ti_viterbi import ViterbiAlgorithm, SequenceState
from map_matching.map_matcher import MapMatcher
from map_matching.candidate_point import get_candidates
from common.spatial_func import distance
from common.trajectory import STPoint, Trajectory
from map_matching.utils import find_shortest_path
from map_matching.route_constructor import construct_path
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值