When I input _
or __
in the python shell I get values returned. For instance:
>>> _
2
>>>__
8
What is happening here?
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.
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.
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.
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”).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With