What Is The Meaning Of Underscore In Python

The underscore character (“_”) serves several purposes and has different meanings depending on how it is used. Here are some of the common uses of underscores in Python:

  1. Variable Naming Convention: A single underscore at the beginning of a variable or function name is a convention used to indicate that the variable or function is intended for internal use within a module or class. It’s a way to signal to other developers that the variable or function is not part of the public API and should not be used outside of its intended scope.
_internal_variable = 42
def _private_function():
    passCode language: Python (python)
  1. Unused Variable Placeholder: If you have a variable that you don’t intend to use, you can name it with a single underscore to indicate that it’s intentionally unused. This can make your code more readable and avoid warnings from code analysis tools.
unused_variable, _ = some_function_returning_a_tuple()Code language: Python (python)
  1. Internationalization (i18n) and Localization (l10n): In the context of string internationalization and localization, underscores are often used to mark string keys that will be replaced with translated text. For example, you might have:
localized_string = gettext("Hello, _username_!")Code language: Python (python)
  1. Name Mangling in Classes: Double underscores at the beginning of an identifier within a class are used for name mangling. This is a technique that allows a class to make its attributes less accessible to outside code. The name of the attribute is modified to include the class name, which can help avoid naming conflicts in subclasses.’
class MyClass:
    def __init__(self):
        self.__private_variable = 42Code language: Python (python)
  1. Numeric Literal Separators (Python 3.6+): Underscores can be used to improve the readability of large numbers by separating thousands, millions, etc., with underscores.
large_number = 1_000_000Code language: Python (python)
  1. Wildcard Imports: An underscore can be used as a placeholder for a module or variable when doing wildcard imports, indicating that you’re importing it just to satisfy the import mechanism, but you don’t intend to use it directly.
from my_module import _  # Import my_module, but don't use it directlyCode language: Python (python)

Remember that while the above uses are common conventions, the meaning of underscores can vary based on the context in which they’re used. Always refer to the official Python documentation or specific coding style guidelines for the project you’re working on for precise guidance on how underscores should be used.

What is the __ before a function in Python?


A double underscore before a function name in Python indicates name mangling. Name mangling is a mechanism that changes the name of a class member in order to make it less likely to cause naming conflicts with subclasses.

When a class attribute or method name is preceded by double underscores and followed by at most one underscore (e.g., __my_function), Python internally modifies the name to include the class name as a prefix, with an additional underscore. This helps to avoid accidental overriding of attributes or methods in subclasses.

Here’s an example to illustrate name mangling:

class MyClass:
    def __init__(self):
        self.__private_variable = 42

class MySubclass(MyClass):
    def __init__(self):
        super().__init__()
        self.__private_variable = 23

obj = MySubclass()
print(obj.__dict__)  # This will show the dictionary of object attributesCode language: Python (python)

In the above example, the double underscore in the __private_variable attribute of both MyClass and MySubclass will be modified to _MyClass__private_variable and _MySubclass__private_variable, respectively.

However, it’s important to note that name mangling is not intended to provide strict encapsulation or security; it’s primarily a tool to avoid unintentional attribute/method name conflicts. Developers can still access the “mangled” names if they really want to, but it’s considered a best practice to respect the intent of name mangling and treat those attributes as private.

What is __ name __ in Python?

In Python, the __name__ attribute is a built-in variable that provides information about the namespace in which a Python script or module is being executed. It’s a special variable that holds the name of the current module or script.

When a Python script is executed, the __name__ attribute is automatically set based on how the script is being used:

  1. If a script is being run as the main program (i.e., it’s the entry point of execution), the __name__ attribute is set to "__main__".
  2. If a script is being imported as a module into another script, the __name__ attribute is set to the name of the module.

This distinction is useful when you want to write code that can be both used as a standalone script and imported as a module into other scripts.

Here’s an example to illustrate this concept:

Consider you have two Python scripts: main_script.py and module_script.py.

# main_script.py
print("This is the main script.")

if __name__ == "__main__":
    print("This code is executed only when main_script.py is run directly.")

# module_script.py
def hello():
    print("Hello from the module script.")

if __name__ == "__main__":
    print("This code is executed only when module_script.py is run directly.")
Code language: Python (python)

Now, if you run main_script.py directly:

$ python main_script.py
This is the main script.
This code is executed only when main_script.py is run directly.
Code language: Python (python)

If you import module_script.py into another script:

# another_script.py
import module_script

module_script.hello()
Code language: Python (python)

When you run another_script.py:

$ python another_script.py
Hello from the module script.Code language: Python (python)

As you can see, the __name__ attribute allows you to write code that behaves differently based on whether it’s being run as the main program or imported as a module. This is commonly used to provide example usage or testing code within a module that won’t run when the module is imported into other scripts.

Can Python variables start with _?


Yes, Python variables can start with an underscore (). In fact, variables that start with a single underscore () are considered valid variable names in Python. However, such variable names are often used to convey that the variable is meant for internal use within a module or class and is not part of the public API.

For example, consider the following code:

_internal_variable = 42

def _private_function():
    passCode language: Python (python)

In this case, _internal_variable and _private_function are valid variable and function names, respectively, but the leading underscore indicates that they are intended for internal use within the module where they are defined. This is a common naming convention in Python to indicate that certain parts of the code are not meant to be accessed directly by users of the module.

While using single underscores at the beginning of variable names is allowed and meaningful, you should be aware that it’s a convention and not a strict rule enforced by the Python interpreter. It’s a way to communicate intent and readability to other developers who might work with your code.

Read More;

  • Muhammad Nabil

    I am a skilled and experienced Python developer with a huge passion for programming and a keen eye for details. I earned a Bachelor's degree in Computer Engineering in 2019 from the Modern Academy for Engineering and Technology. I am passionate about helping programmers write better Python code, and I am confident that I can make a significant contribution to any team. I am also a creative thinker who can come up with new and innovative ways to improve the efficiency and readability of code. My specialization includes Python, Django, SQL, Apache NiFi, Apache Hadoop, AWS, and Linux (CentOS and Ubuntu). Besides my passion for Python, I am a solo traveler who loves Pink Floyd, online video games, and Italian pizza.

    View all posts

Leave a Comment