Python: 如何阻止用户通过另一个模块调用模块(通过属性)?

Python: How to block user from calling module via another module(by attributing it)?

我的模块中有一个 python 库 os。但是,我不希望用户像这样调用 osmy_module.os。我需要 exec() 的这个限制,以允许用户只使用指定的模块。也许可以用 AST 来完成。 如何正确检查代码以发现类似情况?还是不可能?

您可以制作 my_module 具有以下结构的 python 包。

my_module/
|-- __init__.py
|-- my_module.py

例如 my_module.py 具有以下结构。

import os

def function_one():
.
.
.


def function_two():
.
.
.

现在里面__init__.py

from my_module import function_one, function_two

现在,当您在 example.py 中导入 my_module 时,您将只能使用 function_onefunction_two

example.py 文件:

import my_module

my_module.function_one()    #runs without issues

my_module.os    #throws attribute error