views:

80

answers:

3

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.

+3  A: 

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

sth
This is how to do it in Python. Python is deliberately designed with a "consenting adults" development philosophy. If someone wants to import `SimilarSpamClass` or `_SimilarSpamClass`, they can, with the caveat that you warned them.
jcdyer
+7  A: 

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
Nadia Alramli
Thanks. That helps. One other problem is that I am importing a class from module B into module A as well (that I don't want users of module A to access, but it because immediately available upon importing it from module B.
orokusaki
I suppose I could import it as `from moduleb import SpamClass as _SpamClass`
orokusaki
+3  A: 

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.

Tendayi Mawushe