Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what do _ and __ mean in PYTHON

Tags:

python

When I input _ or __ in the python shell I get values returned. For instance:

>>> _
2
>>>__
8

What is happening here?

like image 964
tdolydong Avatar asked Jan 03 '14 15:01

tdolydong


People also ask

Why is __ used in Python?

1. Use in Interpreter. Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want.

What does _ mean in Python class?

The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8. This isn't enforced by Python. Python does not have strong distinctions between “private” and “public” variables like Java does.

What do 2 underscores mean in Python?

Double underscores are used for fully private variables. According to Python documentation − If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores.

What's the meaning of underscores (_ & __) in Python variable names?

Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).


2 Answers

If you are using IPython then the following GLOBAL variables always exist:

  • _ (a single underscore): stores previous output, like Python’s default interpreter.
  • __ (two underscores): next previous.
  • ___ (three underscores): next-next previous.

Read more about it from IPython documentation: Output caching system.

like image 132
Martin Avatar answered Oct 14 '22 08:10

Martin


Theoretically these are just ordinary variable names. By convention, a single underscore is used as a don't care variable. For example, if a function returns a tuple, and you're interested only in one element, a Pythonic way to ignore the other is:

_, x = fun()

In some interpreters _ and __ have special meanings, and store values of previous evaluations.

like image 32
BartoszKP Avatar answered Oct 14 '22 08:10

BartoszKP