_func (), any functional use of underscore? (Python)

I created two modules, one with

def _func():
    print "hi"

      

and further

def func():
    print "hi"

      

When I use the help function on a module including the first function, the help module does not display that function. In contrast to the second example, where this function appears in the help output. Is there any functional difference other than using a helper function?

+3


source to share


4 answers


Yes, there is a (admittedly subtle) difference in functionality. Suppose you have a module A.py :

foo = 1
_bar = 2

      

Note:

>>> 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 behavior, if you do import *

, is that no leading underscore members are imported. You can override this behavior by specifying __all__

:



__all__ = ['foo', '_bar']

foo = 1
_bar = 2

      

Now:

>>> from A import *
>>> (foo, _bar)
(1, 2)

      

By the way, __all__

also overrides the attendee list shown help()

or pydoc

:

$ pydoc A | cat
 ...
DATA
    __all__ = ['foo', '_bar']
    _bar = 2
    foo = 1
 ...

      

+11


source


There is a difference in the names of modules looking at "_" s: they are not exported when you use from module import *

-

This behavior can be overridden by providing the module with a named list __all__

that lists all the attributes that you want to export from the module.

Though:



import module
module._func

      

will work without any difference. As the other answers suggest: "_" is an indicator that the name shouild is reserved for private use of the module / class / API, however in the only case "from module import" and "Offline help" - as you do in your case, the interpreter does this otherwise.

+3


source


Underscores are a convention commonly used to indicate a private member of a module or class.

+2


source


It is a python convention that any names that start with an underscore are not considered part of the public api, so users of a module or class that contain functions that start with an underscore will not be exposed to the existence of those functions with normal access. Of course, since this is just a convention, it can be bypassed, but as a general rule, you can consider everything from underscore to be hidden from code outside the module / class.

Here's some more information from the python documentation: http://docs.python.org/tutorial/classes.html#tut-private

+2


source







All Articles