Private/public module members

E

Elbert Lev

Hi, all!

In accordance with Python documentation, there are 2 ways to hide
data/methods inside the module (make them private):

1. have "public" members defined in __all__ list
2. start "private" members names with underscore.

Both methods for some reason "behave strange".

Here are 2 modules and the output:

#file: main.py ########################
import foo
print dir(foo)
foo.b()
foo._c()
foo.a()

#file: foo.py######################
import sys
__all__ = ["a"]
_private = 56
def b(): print 'b'
def _c(): print '_c'
def a(): print 'a'

Run main.py and here is the output:

['__all__', '__builtins__', '__doc__', '__file__', '__name__', '_c',
'_private', 'a', 'b', 'sys']
b
_c
a

Not only doc(foo) has '_c', '_private' and 'b', but one can call them
from outside the module.
It this "by design"?
 
L

Larry Bates

Absolutely! The "hiding" of private attributes/methods
doesn't make them completely unreachable. It just makes
them slightly "invisible". There is a third method of
"hiding" attributes/methods that is done by putting two
underscores (e.g. __attribute). This gets name mangled
to make it harder to call, but it can still be reached
if you know how. Unlike other languages Python always
allows you to get to the attributes/methods of a class,
even when they are "private". You should always reference
private attributes/methods with care.

Larry Bates
Syscon, Inc.
 
D

Duncan Booth

(e-mail address removed) (Elbert Lev) wrote in
Not only doc(foo) has '_c', '_private' and 'b', but one can call them
from outside the module.
It this "by design"?

Yes.

All that prefixing with an underscore or listing names in '__all__' is
intended to do is to modify the behaviour of 'from foo import *'. It does
not prevent access, or even restrict visibility in any way.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top