英文:
Having python package and module of same name
问题
想象一下,我有一个名为foo的Python包,在其中有许多模块bar1、bar2...
在调用以下语句之后,我可以访问它的函数:
import foo
然后使用以下方式:
foo.bar1.some_function()
现在有一些适用于整个包foo的通用函数。我想将其访问为模块foo,这样我可以使用以下方式调用其函数:
foo.some_often_used_function()
但是,此时foo将成为一个模块而不是一个包,无法同时兼顾两者。
是否有一些解决方法来启用这种语法?使用Python 3.11
英文:
Imagine I have a python package called foo, inside are many modules bar1, bar2...
I can access its functions after calling
import foo
and then with
foo.bar1.some_function()
Now there are a few functions that are general for the whole package foo. I would like to access it as module foo, that I can call its functions with
foo.some_often_used_function()
but then foo would be a module and not a package, it can't be both at the same time.
Is there some workaround to enable this syntax? Using python 3.11
答案1
得分: 1
我成功解决了这个问题,通过在__init__.py中直接编写这些函数。或者在__init__.py中
from foo.foo import *
然后将函数放在
foo/foo.py
英文:
I managed to solve the issue by writing the functions direclty in init.py. Or in init.py
from foo.foo import *
and then have the functions in
foo/foo.py
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论