You cannot hide the methods and attributes of objects. If you want to be sure that your internal methods are not displayed, completing the migration is the way to go:
class PublicC: def __init__(self): self._c = C() def public(self): self._c.public()
Double underscoring as a prefix is ββusually discouraged, as far as I know, to prevent collision with python's internal components.
Fault-tolerant are __myvar__
names with double underscore + suffix ... this naming style is used by many python internal components and should be avoided - Anentropic
If you prefer subclassing, you can overwrite internal methods and cause errors:
class PublicC(C): def internal(self): raise Exception('This is a private method')
If you want to use python magic, you can take a look at __getattribute__
. Here you can check what your user is trying to get (function or attribute), and raise an AttributeError
if the client wants to use an internal / blacklist.
class C(object): def public(self): print "i am a public method" def internal(self): print "i should not be exposed" class PublicC(C): blacklist = ['internal'] def __getattribute__(self, name): if name in PublicC.blacklist: raise AttributeError("{} is internal".format(name)) else: return super(C, self).__getattribute__(name) c = PublicC() c.public() c.internal()
I assume this causes the least code overhead, but also requires some maintenance. You can also change the validation methods and whitelists .
... whitelist = ['public'] def __getattribute__(self, name): if name not in PublicC.whitelist: ...
This might be better for your case, since the whitelist probably won't change as often as the blacklist.
In the end, it is up to you. As you said yourself: all about documentation.
Another note:
You might also want to rethink your class structure. You already have a factory F
class for C
Let F
have all the internal methods.
class F: def build(self): c = C() self._internal(c) return c def _internal(self, c):
In this case, you do not need to wrap or subclasses. If there are no strict design constraints to make this impossible, I would recommend this approach.