如何限制Python模块以暴露特定零件
我只是在Python中制作了一个模块,但我不希望人们这样做:
import mymodule
mymodule.
然后,这显示了我添加到模块中的所有方法和变量。我只希望他们看到指定的,因为我还有许多仅供内部用途的额外。
I just made a module in python but I don't want people to do this:
import mymodule
mymodule.
and this then shows all methods and variables I added to the module. I just want them to see specified ones because I have many additional ones that are only for internal use.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果这是您的模块
myModule.py
:直接导入它:
让用户访问
myModule.expose_this()()
andmymodule.but_not_this()代码>,无法更改它,尽管您可以调用
but_not_this
_but_not_this
之类的东西,而许多编辑至少会警告用户,他们不应该访问该用户。但是,正确的方法是创建一个软件包。 添加
__ INT __。
将您的模块放入单独的文件夹中(称为
myModule
),然后 他们只能访问myModule.expose_this()
关于创建软件包以及如何添加内容还有很多要说的话,但是在那里有很好的文档和教程。
注意:如果有人知道模块的内部结构,则他们仍然可以访问
but_not_this()
:由于有人需要,因此无论如何都可以使用您的代码。但是,如果您想明确意图,则可以重命名
myModule.py
_mymodule.py ,并将您不希望与_暴露的功能前缀
也是 - 这可以帮助编辑者加强与用户的意图。If this is your module
mymodule.py
:Importing it directly like this:
Gives a user access to
mymodule.expose_this()
andmymodule.but_not_this()
, there's no way to change that, although you could callbut_not_this
something like_but_not_this
instead and many editors would at least warn a user that they are not supposed to access that.However, the right way to do it would be to create a package. Put your module in a separate folder (called
mymodule
), and add an__init__.py
with this:Now, if someone imports your package using the same import statement as before, they only have access to
mymodule.expose_this()
There's a lot more to say about creating packages and how to add content, but there's good documentation and tutorials for that out there.
Note: if someone knows the internal structure of your module, they can still access
but_not_this()
with this:But they'd have to really want to - making it impossible is hard and there's really no point, since someone will be able to get at your code anyway, if they need to. But if you want to make the intent clear, you could rename
mymodule.py
to_mymodule.py
and prefix the functions you don't want exposed with a_
as well - this helps editors to reinforce your intentions with the user.