Why does python not have a mechanism for data hiding?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Jun 5 07:53:55 EDT 2008


Russ P. a écrit :
>(snip)
> (answering to Carl Bank) I thought you were saying that encapsulation or so-called "data
> hiding" is worthless.

As far as I'm concerned, I view encapsulation as very desirable, and 
data-hidding as totally worthless when applied to Python's object model.

> Here's what I think Python should have. I think it should have a
> keyword, something like "priv," to identify data or functions as
> "private." As I said earlier, "private" for class data or functions
> ("methods") could be implemented like "protected" in C++. That means
> that derived classes would have access to it, but clients of the class
> would not. If the client really needs or wants access, he could be
> given a sort of "back door" access similar to the current Python rule
> regarding double leading underscores. Thus, the client would have
> access, but he would know very well that he is using something that
> the original designer did not intend for him to use.


> It's just a suggestion. I'm not a language expert, and I realize that
> I could be missing something important.

Given your very recent discovery of what 'dynamic' *really* means in 
Python (like, for exemple, dynamically adding / replacing attributes - 
including methods - on a per-class or per-instance basis), possibly, yes.

> I also realize, by the way, that Python allows a client of a class to
> define a new class member from completely outside the class
> definition. Obviously, that cannot be declared private.

Why so ?

> But if the
> same identifier is already declared private within the class, than the
> new definition should not be allowed (because it would defeat the
> whole idea of "private" class members).

Why so ?

Metaprogramming (including monkeypatching) is part of the pythoneer's 
toolbox, and while it's not something to use without pretty good 
reasons, it has many times proven to be a real life saver. In languages 
not allowing it, the solutions to the class of problems easily solved by 
monkeypatching happens to be at best a kludge, at worst plain 
unsolvable, at least without too much effort to be even worth it. Your 
above proposition would arbitrarily make possible and useful things 
either uselessly complicated or near impossible.



More information about the Python-list mailing list