使util文件无法在python中访问

问题描述

我正在构建一个python库。我想为用户提供的功能在stemmer.py中。 Stemmer.py使用stemmerutil.py

我想知道是否有一种方法使用户无法访问stemmerutil.py。

directory's snapshot

解决方法

如果您想向用户隐藏实施细节,您可以采取两种方法。第一种使用约定来表示什么是公共API的一部分,哪些不是公共API,另一种是hack。


在python库中声明API的约定是将所有应公开到最高__init__.py的{​​{3}}中的类/函数/名称添加。它并没有做很多有用的事情,如今它的主要目的是一个象征性的“请使用此功能,别无其他”。您的看上去可能像这样:

urdu/urdu/__init__.py

from urdu.stemmer import Foo,Bar,Baz
__all__ = [Foo,Baz]

为强调这一点,您还可以在stemmerUtil.py __all__-list内的名称前加上所有定义,例如def privateFunc(): ...成为def _privateFunc(): ...


但是您也可以通过将其作为资源而不是包中的模块并将其动态加载,从而将其隐藏在解释器中。这是一个hack,可能不是一个好主意,但在技术上是可能的。

首先,将stemmerUtil.py重命名为stemmerUtil-现在它不再是python模块,并且无法使用import关键字导入。接下来,在stemmer.py

中更新此行
import stemmerUtil

使用

import importlib.util
import importlib.resources  
# in python3.7 and lower,this is importlib_resources and needs to be installed first


stemmer_util_spec = importlib.util.spec_from_loader("stemmerUtil",loader=None)
stemmerUtil = importlib.util.module_from_spec(stemmer_util_spec)

with importlib.resources.path("urdu","stemmerUtil") as stemmer_util_path:
    with open(stemmer_util_path) as stemmer_util_file:
        stemmer_util_code = stemmer_util_file.read()
exec(stemmer_util_code,stemmerUtil.__dict__)

运行此代码后,可以像导入stemmerUtil模块一样使用ALTER TABLE dbo.MyTable ALTER COLUMN MyString VARCHAR(50) COLLATE Latin1_General_100_CI_AI_SC_UTF8 模块,但是安装包的任何人都看不到它-除非他们也运行此确切的代码。

但是正如我说的,如果您只想与用户进行交流,则您的软件包的哪一部分是公共API,那么第一种解决方案就更可取了。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...