【问题标题】:How to get parent module/package functions in namespace of child package/module in Python?如何在 Python 中子包/模块的命名空间中获取父模块/包函数?
【发布时间】:2020-05-02 04:04:11
【问题描述】:

我有一个非常复杂的模块,我想将子包分解成单独的包。我的第一次尝试将是“实用程序”子模块。我希望能够将父包example_utils.py 中的所有内容导入example_module.utils,但我也希望example_module.utils 也有自己的功能。

最后我希望能够做到以下几点:

import example_module as em
x = 10
y1 = em.utils.f_parent1(x)
y2 = em.utils.f_child1(x)

# and do this 
from example_module.utils import f_parent1, f_child1

# and use the parent module as a standalone
from example_utils import f_parent1, f_parent2

如何构建我的子模块 example_module 以具有此功能?**

模块实用程序保存为单独的独立模块example_utils.py

def f_parent1(x):
    return x

def f_parent2(x,y):
    return x+y

这个模块将安装在我的环境中:

pip install path/to/example_module

更大的模块 (example_module) 使用 example_utils 作为依赖项

# Directory structure for larger Module

example_module
|++++| __init__.py
|++++| utils  
|++++| ++++ | __init__.py
|++++| ++++ | utils.py

|++++| ++++ | __init__.py的内容

from .utils import *

|++++| ++++ | utils.py的内容

from example_utils import * 

def f_child1(x):
    return x**2

|++++| __init__.py的内容

__version__= "0.1"
__developmental__ = True

# Utilities
from .utils import utils

# =======
# Direct Exports
# =======
_submodules = ["utils"]
__all__ = sorted(__all__)

如果namespace 不是正确的术语,请提前道歉。我对namespacescope 等感到困惑。

【问题讨论】:

  • f_parent1 在两个模块中实际上是相同的函数,因为它们引用的是相同的东西。因此,即使给 f_parent1 一个不同的名称,除了创建一个额外的引用之外,没有任何用处。
  • 我明白,但我想让它向后兼容我的旧笔记本。
  • 如果是这样,from example_module.utils import f_parent1 as em_f_parent1; from example_utils import as eu_f_parent1 会解决您的问题吗?否则我不太确定我是否理解这个问题。如果您需要父母和孩子之间的单独引用,他们不能f_parent1
  • 嗯...我明白你在说什么。我尝试将父模块加载到子模块的名称空间的原因是因为我需要筛选数千行代码来修复这些错误。我可以在导入中发挥一些作用,但如果可能的话,我真的很想拥有这个功能。即使这不是解决这种情况的最佳方法,您知道如何使这成为可能吗?
  • 我还是有点困惑。也许如果您可以提供一个用例,其中f_parent1 需要在父母和孩子之间明显不同,那么它会有所帮助。同时,另一种方法是引用这样的函数:import module1 as m1, module2 as m2,然后通过func = 'f_parent1'; getattr(m1, func); getattr(m2, func)引用函数。正确的方法是只使用m1.f_parent1m2.f_parent1,但如果您需要 使用一个名称来引用函数,这是一种方法。

标签: python import module namespaces package


【解决方案1】:

根据@r-ook 的建议,我发现我可以使用getattr 从父模块中按字符串名称获取函数。之后,我可以将函数添加到命名空间?范围?的子模块。

example.py

from example_utils import as emu


functions_from_parent = ["f_parent1", "f_parent2"]

__all__ = {"f_child1"}

for function_name in functions_from_parent:
    globals()[function_name] = getattr(emu, function_name)
    __all__.add(function_name)
__all__ = sorted(__all__)

def f_child1(x):
    return x**2

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多