[Tutor] Implementing data hiding in Python
Michael P. Reilly
arcege@shore.net
Tue, 11 Jul 2000 22:27:11 -0400 (EDT)
> I don't want to get into religious wars re the benefits of
> encapsulation and the use of 'private', 'const' or whatever. I know that I
> can use 'name-mangling' via '__foo' from Python 1.5 to give me a limited
> form of privacy and I have seen allusions to extensions that enforce data
> hiding :
>
> There is little direct support for data hiding within Python itself, but
> extensions and embeddings of Python can provide rock solid interfaces that
> expose only permitted foreign operations to the Python interpreter. Python's
> restricted execution mode may also provide some (usually extreme) protection
> within the interpreter itself.
>
> I need to know if anyone has written said extensions, as I am unable
> to find anything at the Vaults of Parnassus archive. I suspect that the
> above quote may indicate that we need to write our own extensions to enforce
> data-hiding on a class-by-class basis, but I'm open to suggestions. The
> issue is *not* coding to prevent breaking modules by trampling one anothers
> namespaces, it is convincing management that Python is the right tool for
> the bulk of the project.
There is _no_ support for data hiding. The philosophy is based on
introspection, not hiding. There are means that can "hide" values, but
it gets into carefully constructed __getattr__ and __setattr__
methods (there are issues with subclassing).
Extensions enforce nothing in terms of data hiding, but.. as much or
as little as the developer decides can be exposed. Extensions create
Python types, not classes. You can make wrapper classes around the
types (like UserList and UserDict).
For documentation on making extensions you can read:
"Extending and Embedding"
http://www.python.org/doc/current/ext/ext.html
"Python/C API"
http://www.python.org/doc/current/api/api.html
and (listed in the Vaults) "How to Write a Python Extension"
http://starship.python.net/crew/arcege/extwriting/pyext.html
SWIG can make this happen a little better, but with a little overhead
and limitations.
If you are looking for easy data hiding, Python might not be the
language to go with. But then, data hiding is rarely a good reason to
go with a language.
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------