Python:如何禁止从模块导入类?
我尝试过:
__all__ = ['SpamPublicClass']
但是,当然这只是为了:
from spammodule import *
有没有办法阻止类的导入。我担心有人会编写我的代码的 API 级别的混乱:
from spammodule import SimilarSpamClass
这会导致调试混乱。
I tried:
__all__ = ['SpamPublicClass']
But, of course that's just for:
from spammodule import *
Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write:
from spammodule import SimilarSpamClass
and it'll cause debugging mayhem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
约定是使用 _ 作为前缀:
如下:
不会导入 _PrivateClass。
但这不会阻止他们进口它。他们仍然可以显式导入它。
The convention is to use a _ as a prefix:
The following:
Will not import the _PrivateClass.
But this will not prevent them from importing it. They could still import it explicitly.
私有类的名称以 和 下划线开头,这样通过名称就可以清楚地表明它不供公共使用。这实际上不会阻止任何人导入该类,但它不应该偶然发生。这是一个公认的约定,以下划线开头的名称是“内部”的。
Start the names of private classes with and underscore, so that it will be clear just by the name that it is not for public use. That will not actually prevent anybody from importing the class, but it shouldn't happen by accident. It's a well established convention that names starting with an underscore are "internal".
在 Python 中,没有办法真正阻止对模块内容或类内容的访问。 此类事情按惯例处理将您的类命名为
_SimilarSpamClass
(带有前导下划线),以向调用者表明这是您模块的实现细节,而不是模块的一部分发布的API。在 Python 中将某些内容标记为“私有”正确记录您的公共 API,以便其他开发人员知道如何正确使用您的模块并遵循标准命名约定,以便模块的用户很容易注意到他们何时偏离了 API 并转向了实现。
There is no way to actually block access to the contents of a module or the contents of a class for that matter in Python. This sort of thing is handled by convention name your class
_SimilarSpamClass
(with a leading underscore) to indicate to callers that this is an implementation detail of your module and not part of the published API.To mark something as "private" in Python properly document your public API so other developers know how to use your module correctly and follow the standard naming conventions so that users of your module easily notice when they have strayed from your API to your implementation.