有相同名称的Python软件包和模块

huangapple go评论53阅读模式
英文:

Having python package and module of same name

问题

想象一下,我有一个名为foo的Python包,在其中有许多模块bar1bar2...

在调用以下语句之后,我可以访问它的函数:

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

huangapple
  • 本文由 发表于 2023年6月19日 18:08:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定