使util文件在python中不可访问

2024-09-30 00:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个python库。我希望用户可以使用的函数在stemmer.py中。Stemmer.py使用stemmerutil.py

我想知道是否有办法让用户无法访问stemerutil.py

directory's snapshot


Tags: 函数用户py办法stemmerstemmerutilstemerutil
1条回答
网友
1楼 · 发布于 2024-09-30 00:40:29

如果您想对用户隐藏实现细节,有两种方法可供选择。第一种使用约定来表示什么是公共API的一部分,什么不是公共API的一部分,另一种是黑客攻击


在python库中声明API的约定是添加所有应公开到最顶层__init__.py^{}-list中的类/函数/名称。它没有做那么多有用的事情,现在它的主要用途是象征性的“请用这个,别用别的”。你的可能看起来有点像这样:

urdu/urdu/__init__.py

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

为了强调这一点,您还可以在stemmerUtil.py{a2}中的所有定义前面给出它们的名称,例如def privateFunc(): ...变成def _privateFunc(): ...


但是,您也可以通过将代码作为资源而不是包中的模块并动态加载来对解释器隐藏代码。这是一个黑客,可能是一个坏主意,但它在技术上是可能的

首先,将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模块,但安装包的任何人都看不到它,除非他们也运行此代码

但是正如我所说的,如果您只想与您的用户交流您的包的哪一部分是公共API,那么第一个解决方案是非常可取的

相关问题 更多 >

    热门问题