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__)
如果您想对用户隐藏实现细节,有两种方法可供选择。第一种使用约定来表示什么是公共API的一部分,什么不是公共API的一部分,另一种是黑客攻击
在python库中声明API的约定是添加所有应公开到最顶层}-list 中的类/函数/名称。它没有做那么多有用的事情,现在它的主要用途是象征性的“请用这个,别用别的”。你的可能看起来有点像这样:
__init__.py
的^{urdu/urdu/__init__.py
为了强调这一点,您还可以在
stemmerUtil.py
{a2}中的所有定义前面给出它们的名称,例如def privateFunc(): ...
变成def _privateFunc(): ...
但是,您也可以通过将代码作为资源而不是包中的模块并动态加载来对解释器隐藏代码。这是一个黑客,可能是一个坏主意,但它在技术上是可能的
首先,将
stemmerUtil.py
重命名为stemmerUtil
——现在它不再是python模块,不能使用import
关键字导入。接下来,在stemmer.py
中更新这一行与
运行此代码后,可以像导入一样使用
stemmerUtil
模块,但安装包的任何人都看不到它,除非他们也运行此代码但是正如我所说的,如果您只想与您的用户交流您的包的哪一部分是公共API,那么第一个解决方案是非常可取的
相关问题 更多 >
编程相关推荐