Truly Private Variables in Python 3
You can get nearly the same effect without the fancy inspection by using closures instead of attributes.
class Foo:
def __init__(self):
private = 'bar'
def print_private():
print(private)
self.print_private = print_private
foo = Foo()
foo.print_private() # works
foo.private # kaboom
Of course, inspect
can see into closures too.
I have tried overriding getattribute, but the problem is that there is no way to tell if the call is coming from inside the class or not (that I am aware of).
You can use the inspect
module to find the name and module of the calling function, which you could compare against a whitelist.
But inspect
also has getattr_static
, which can bypass any __getattribute__
.
Nothing is truly private in Python. There are ways to make access difficult, but there are always ways around those ways.
The only solution then, is outside of the current Python interpreter. You could use a foreign function interface to some other more secure language or a remote procedure call (e.g. xmlrpc) to the same or to another Python interpreter running in a subprocess, or even one running as a different user with different permissions. The private variable and all the functions allowed to access it will live outside the current interpreter. Then there's no way to inspect it.
This type of privilege separation is even one of the stated use cases for the Pyro RPC library.