What is the purpose of python variables __something__
e.g. __name__
, __file__
I often see them in real python programs. Is there a list of these variables?
thank you
What is the purpose of python variables __something__
e.g. __name__
, __file__
I often see them in real python programs. Is there a list of these variables?
thank you
PEP8 covers this:
In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):
_single_leading_underscore: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes FooBar_boo; see below).
__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.
The final bullet point is pertinent.
Is there a list of these variables?
I doubt that there is an official list of all such double leading and trailing underscore names, but I could not say so for sure.
Check this chapter of Python manual. Does it satisfy you?
They're considered special or magic. The language doesn't prevent you from creating your own, but don't.
Here is a good guide on the magic methods but there are also special attributes, such as __all__
, which is normally pronounced "dunder all" or "under under all".