导入模块的最佳实践是什么:绝对路径还是相对路径?

导入模块的最佳实践是什么:绝对路径还是相对路径?

问题描述:

所以我在做一个项目,我将其他 Python 模块的所有路径都定义为绝对路径:

So I was working on a project where I defined all paths to other Python modules as absolute paths:

import sys
sys.path.append('/home/user123/my_project/utilities')
import file_utilities

但是后来我将项目移到了另一个文件夹,这破坏了一切.我必须手动编辑所有路径以说明文件夹更改.

But then I had move the project to a different folder, which broke everything. I had to manually edit all paths to account for the folder change.

我最初使用绝对路径是一个糟糕的选择吗?我最初避免使用相对路径,因为我认为它很快就会变得丑陋:

Is my initial use of absolute paths a bad choice? I initially avoided relative paths because I thought it would quickly become ugly:

import sys
sys.path.append('../../../../utilities')
import file_utilities

最佳做法是什么?

一个方便的解决方案是移动"一个基本路径,即 basepath = "/home/user123/" 到一个变量中并将路径地址为

A handy solution would be to "move" a basepath, i.e. basepath = "/home/user123/" into a variable and address the path as

sys.path.append('{}/my_project/utilities'.format(basepath))

sys.path.append('{}/my_project/utilities'.format(basepath))

那会使相对符号变得丑陋,并为您提供灵活性.

That would ugly relative notation and give you flexibility.