导入具有冲突模块名称的Python函数和私有函数

时间:2019-03-22 12:20:16

标签: python module package

说我有以下Python软件包目录结构:

package
    sample/
        __init__.py
        a.py

sample/a.py包含一些功能:

def _a(x):
    ...
    return some_result

def _b():
    return 7

def a(x):
    """
    Wrapper for `_a()`
    """
    return _a(x)

def c():
    return _b()

通常,我会打a()

import sample as smp

smp.a.a(5)

但是要使其更简单并且需要更少的键入(因为我的模块名称和函数名称确实更长),我可以使用以下方法修改sample/__init__.py文件:

from .a import a

然后,我现在可以做:

import sample as smp

smp.a(5)

但是,有时候我需要调用其他一些函数,例如_b()c()(例如,对于某些单元测试),但是我不希望这些函数很容易),用户可以通过smp._b()smp.c()访问。因此,用以下内容修改sample/__init__.py不希望的

from .a import a, _b, c

相反,我希望只能以这种方式访问​​其他功能:

import sample as smp

smp.a(5)

# The following lines will error out
smp.a._(5)
smp.a._b()
smp.a.c()

但是,由于smp.a已被定义为函数而不是模块名称,因此这是不可能的。如何在不将其他功能移到单独文件中的情况下执行此操作?

0 个答案:

没有答案
相关问题