
Underscore in Python
The Python underscore (_) has several uses, and its meaning can vary depending on the context. Here are some common uses of the underscore in Python:
- Unused Variable Names: The underscore is often used as a variable name when you don’t intend to use the value. It serves as a placeholder for values that are not needed in a particular code block or loop. For example:
for _ in range(5):
print("Hello")
In this loop, the variable _
is used as a placeholder because we don’t need the loop index value.
- Multiple Unpackings: In unpacking operations, you can use a single underscore to discard values that you are not interested in. For example:
first, _, last = "John Doe".split()
Here, the middle name (if any) is discarded using _
.
- Internationalization (I18N): In internationalization (i18n) and localization (l10n) of software, the underscore is used as an alias for the
gettext
function, which is used for translating messages in Python programs. For example:
from gettext import gettext as _
message = _("Hello, World!")
This usage allows for easier translation of messages into different languages.
- Name Mangling: In Python, a double underscore prefix on an instance variable name causes name mangling. This makes the variable more challenging to access from outside the class. For example:
class MyClass:
def __init__(self):
self.__private_var = 42
obj = MyClass()
print(obj.__private_var) # Raises an AttributeError
In this case, __private_var
is name-mangled to _MyClass__private_var
to prevent accidental access from outside the class.
- “Wildcard” Import: In the context of module imports, the underscore is sometimes used as a wildcard to import all names not starting with an underscore from a module. For example:
from module_name import *
However, this usage is generally discouraged because it can lead to naming conflicts and make the code less readable.
- Unused Loop Variables: When you don’t need the loop variable in a loop, you can use the underscore to indicate that it’s not being used intentionally. For example:
for _ in range(10):
# Do something without using the loop variable
- Type Hinting: In function and variable annotations for type hinting, the underscore can be used as a convention to indicate that a variable is intentionally not annotated. For example:
def my_function(arg1: int, arg2: _) -> _:
# The types of arg2 and the return value are not specified
pass
In this case, _
is used to indicate that the types are intentionally omitted.
It’s important to note that while the underscore has these specific uses in Python, its primary use is as a conventional way to indicate that a variable is not being used in a particular code block. Python itself does not assign any special meaning to the underscore, and it’s not a reserved keyword.