Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does defining a non-class private function means anything in Python?

def __f():
  print 1

def _f():
  print 1

I tried import and it's accessible:

>>> import test1
>>> test1._f()
1

Does it mean anything? I want to write some helper functions which aren't class-based. Then I want to hide certain low-level, concrete functions, and leaving only high-level function (view them as APIs) accessible to users to use.

For example:

test1.copy() will call another helper function in the same file which does some extra checking, but I don't want to expose that to user.

like image 783
CppLearner Avatar asked Dec 01 '22 22:12

CppLearner


1 Answers

The single leading underscore is a Python naming convention. A number of tools rely on that convention. For example help() will ignore single underscored names. Using from somemodule import * will also ignore single underscored names.

The double leading underscore triggers name mangling (prefixing the name with the class name and a single leading underscore). It is used to create thread-local references. That allows intra-class calls that won't be accidentally broken by a subclass. There is a nice example of this in the tutorial at http://docs.python.org/tutorial/classes.html#private-variables .

Lastly, there is the special method naming convention of two leading underscores and two trailing underscores. Those names are used by the interpreter to implement operators and to implement a number of standard protocols (i.e. iterators, context managers, pickling, etc). See http://www.rafekettler.com/magicmethods.html for a nice write-up on the special methods.

like image 115
Raymond Hettinger Avatar answered Dec 14 '22 23:12

Raymond Hettinger