I created two modules, one with
def _func():
print "hi"
and another
def func():
print "hi"
When I use the help function on the module including the first function, the help module doesn't display this function. As opposed the second example where this function shows in the help output. Is there any functional difference aside from the use of the help function?
Yes, there is an (admittedly subtle) difference functionality-wise. Let's assume you have a module A.py:
foo = 1
_bar = 2
Observe:
>>> from A import *
>>> foo
1
>>> _bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_bar' is not defined
The default behaviour if you do an import *
is that members with a leading underscore are not imported. You can override that behaviour by specifying an __all__
list:
__all__ = ['foo', '_bar']
foo = 1
_bar = 2
Now:
>>> from A import *
>>> (foo, _bar)
(1, 2)
By the way, __all__
also overrides the list of members shown by help()
or pydoc
:
$ pydoc A | cat
...
DATA
__all__ = ['foo', '_bar']
_bar = 2
foo = 1
...
It's a python convention that any names starting with an underscore are not considered as part of a public api, thus users of a module or class that contains functions beginning with underscores won't be told about the existence of these functions by normal access. Of course, since it's just a convention, it can be bypassed, but as a general rule of thumb you can consider anything starting with an underscore to be hidden from code outside the module/class.
Here is some more information from the python documentation: http://docs.python.org/tutorial/classes.html#tut-private
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With