优雅导入本地python包?
我非常喜欢 Flutter/Dart 和 Rust 中的本地包管理方法,并希望 Python 中也能存在一些类似的解决方案。
例如,我在 /path/of/the/utility
处有一个 utility
python 包,其中包含数十个 python 文件,在以下位置有一个 myapp
包: /path/to/my/app
。对于 myapp
依赖于 utility
,如果我使用 Flutter/Dart 或使用 Rust,我可以写下这样一行:
utility:
path: /path/of/the/utility
然后愉快地像 import 一样导入它'package:utility/somefile.dart
。 (Rust 的情况类似,所以我不再重复。)
但是,对于 Python,我还没有找到这样的解决方案(pip
似乎不知道这一点;conda
也不知道>)。目前,我必须使用以下丑陋的方法:
// myapp/somefile.py
import sys
sys.path.append('/path/of/the/utility')
import utility
并操作我的 IDE(在我的例子中为 Intellij IDEA),以便它理解此 myapp
包依赖于 utility
包,并且不依赖于 utility
包给我一个大的红色下划线。
备注:可能不可能(是吗?)让 /path
为包根,而 myapp
为子包,因为: (1)myapp 可以是 Django 项目。 (2)如果一个大项目是一个Python包,那么IDE(我的例子是Intellij IDEA)的配置会很困难,因为它与其他语言混合在一起。
问题:我可以采用 Flutter/Dart 或 Rust 方法吗?谢谢!
I like approaches of local package management in Flutter/Dart and Rust very well, and hope there could exist some similar solution in Python.
For example, I have a utility
python package at /path/of/the/utility
containing dozens of python files, and a myapp
package at /path/to/my/app
. For myapp
to depend on utility
, if I were using Flutter/Dart or using Rust, I could write down a line like:
utility:
path: /path/of/the/utility
And then happily import it like import 'package:utility/somefile.dart
. (The Rust case is similar so I do not repeat.)
However, with Python, I have not found out such solution (pip
does not seem to know this; neither is conda
). Currently I have to use the following ugly approach:
// myapp/somefile.py
import sys
sys.path.append('/path/of/the/utility')
import utility
and also manipulate my IDE (Intellij IDEA in my case) such that it understands this myapp
package depends on utility
package and do not give me a big red underline.
Remark: It may not be possible (is it?) to let /path
to be the package root and myapp
to be a subpackage, because: (1) The myapp
, for example, can be a Django project. (2) It will be hard to configure the ide (Intellij IDEA in my case) if the huge project is one Python package since it is mixed with other languages.
Question: Can I do something like the Flutter/Dart or Rust approach? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论