重构python模块配置以避免相对导入 [英] Refactoring python module configuration to avoid relative imports

查看:81
本文介绍了重构python模块配置以避免相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与有关我的上一个问题

我了解如何存储和读取配置文件。有很多选择,例如 ConfigParser ConfigObj

I understand how to store and read configuration files. There are choices such as ConfigParser and ConfigObj.

对此结构进行假设'eggs'模块:

Consider this structure for a hypothetical 'eggs' module:


eggs/
  common/
    __init__.py
    config.py
  foo/
    __init__.py
    a.py

'eggs.foo.a'需要一些配置信息。我目前正在执行的操作是在 a中

'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a',

import eggs.common.config

。这样做的一个问题是,如果将 a移至模块树中的更深层次,则相对导入会中断。绝对导入不需要,但是它们要求您的模块位于PYTHONPATH上。

. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.

上述绝对导入的一种可能替代方法是相对导入。因此,在'a'中,

A possible alternative to the above absolute import is a relative import. Thus, in 'a',

import .common.config

而没有争论相对进口和绝对进口的优缺点,我想知道其他可能的解决方案吗?

Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?

编辑-删除了VCS上下文

edit- Removed the VCS context

推荐答案

导入...要求您的模块位于PYTHONPATH上。

"imports ... require your module to be on your PYTHONPATH"

正确。

那么,设置 PYTHONPATH 怎么了?

这篇关于重构python模块配置以避免相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆