I look at code samples at various sites and I often see variables (or I don’t understand what it is) with the _ character like this. For example: _f or with two __. I do not know Google for what keyword. Code example:

def run_once(f): """ >>> @run_once ... def foo(n): return n + 1 >>> foo(7) 8 >>> foo(0) 8 """ def _f(*args, **kwargs): if not hasattr(_f, "_retval"): _f._retval = f(*args, **kwargs) return _f._retval return _f if __name__ == "__main__": import doctest doctest.testmod() 
  • for a search engine, you can use: "naming conventions", "naming conventions" keywords. - jfs
  • By the way, help('_') works. - jfs

3 answers 3

  1. Name with one underscore _name - by common agreement is used as an analogue of protected , protected name in other languages. In other languages, only class heirs can use this name. In python, this is just an agreement.
  2. The name with two underscores __name is analogous to private (in python it is pseudo- private ), the name is for internal use only inside a module or class. Such names have special protection, and you can only access it from the outside if you know the class in which this attribute is defined.

  3. Names with two underscores on both sides of the name __name__ are "magic" methods that implement some language functionality.

  • Sorry what ? - etki
  • one
    Well, you're right. Only it was not necessary to correct. In each message, someone climbs and reigns. You have some kind of competition right here. - Mr Fix

I advise you to read the official documentation

Names that begin with a single underscore ( _variable ) are intended for internal use.

The same names that begin and end with a double underscore ( __init__ ) are usually already embedded and are only redefined.

    Just used to make the variable _f! = F. Ie variables are similar, but different. This is quite a popular method in python.

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky