Python: How to prevent import of a class from a module?

I tried:

__all__ = ['SpamPublicClass']

But of course, this is just for:

from spammodule import *

Is there a way to block class imports. I am worried about the API level confusion of my code that someone will write:

from spammodule import SimilarSpamClass

and this will lead to debugging chaos.

+3
source share
3 answers

The convention should use _ as a prefix:

class PublicClass(object):
    pass

class _PrivateClass(object):
    pass

Following:

from module import *

Will not import _PrivateClass.

But that will not stop them from importing it. They could still import it explicitly.

from module import _PrivateClass
+10
source

, , , . - , . , , , "".

+6

, Python. _SimilarSpamClass ( ), , , API. p >

To mark something as “private” in Python, correctly document your public API so that other developers know how to use your module correctly and follow the standard naming conventions so that users of your module can easily notice when they deviate from your API to your implementation.

+5
source

Source: https://habr.com/ru/post/1730880/


All Articles