Python 包中的共享函数放在哪里?

Where to put shared functions in a Python Package?

我正在创建一个供内部使用的 python 程序包,它具有一些在其他模块中通用的内部功能。例如,下面的函数正在其他模块中使用 -

def GetLocalImage(WebImage):
  ImageLink = WebImage.get("data-src")
  FileName = ImageLink.split("/")[-1]
  urllib.request.urlretrieve(ImageLink,FileName)
  return(FileName)

如您所见,函数需要使用 urllib。下面是包的文件结构-

formatter
\ __init__.py
\ File1.py    --> It would call GetLocalImage()
\ File2.py    --> It would call GetLocalImage()

我的主程序使用了from formatter import *语句。我的问题是 -

  1. import urllib 和函数的正确位置是什么?
  2. 我需要修改包结构吗?

我终于明白了。这是我解决它的方法-

  1. 我将共享函数保存到另一个文件common.py
  2. common.py 中,我 import urllib.request
  3. File1.pyFile2.py 中,我导入了 from .common import *
  4. 在主程序中,就是import formatter
  5. __init__.py 文件中,我保留了 -
from .common import *
from .File1 import *
from .File2 import *

我想我们可以跳过 __init__.py 文件(不确定)。希望这对以后的人有帮助。