Question

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.

Was it helpful?

Solution

The convention is to use a _ as a prefix:

class PublicClass(object):
    pass

class _PrivateClass(object):
    pass

The following:

from module import *

Will not import the _PrivateClass.

But this will not prevent them from importing it. They could still import it explicitly.

from module import _PrivateClass

OTHER TIPS

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".

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top