underscores in Python,

Question

Answers ( 1 )

  1. In Python, underscores are used in several contexts, each with its own meaning:

    1. Single Leading Underscore: _var

    A single leading underscore before a variable or method name is a convention to indicate that the entity is intended for internal use. This is more of a convention than a strict rule enforced by the Python interpreter. Names prefixed with an underscore are not imported by a statement such as from module import *.

    class MyClass:
        def _internal_method(self):
            pass
    

    2. Single Trailing Underscore: var_

    A single trailing underscore is used by convention to avoid naming conflicts with Python keywords. This usage is to prevent conflicts with the names of built-in or reserved words in Python.

    def function(class_):  # Avoids conflict with the 'class' keyword
        pass
    

    3. Double Leading Underscore: __var

    A double leading underscore triggers name mangling in class attributes. This is used to avoid name conflicts in subclasses. The interpreter changes the variable name in a way that makes it harder to create subclasses that accidentally override the private attributes and methods of their superclasses.

    class MyClass:
        def __init__(self):
            self.__private_var = 42
    
        def __private_method(self):
            pass
    

    In this example, __private_var and __private_method are not directly visible outside MyClass due to name mangling.

    4. Double Leading and Trailing Underscore: __var__

    Names that have both leading and trailing double underscores are magic objects or attributes that Python language assigns special meaning to. They are also known as "dunder" methods (short for "double underscore").

    class MyClass:
        def __init__(self, value):
            self.value = value
    
        def __str__(self):
            return str(self.value)
    

    In this example, __init__ is the constructor method, and __str__ is called by the str() built-in function and by the print statement to obtain a string representation of the object.

    5. Single Underscore: _

    A single underscore by itself is used as a temporary or insignificant variable name. This is commonly seen in unpacking values where some of the values are not needed, or in internationalization (i18n) to mark strings for translation. It is also used in the interactive interpreter to reference the last returned result.

    for _ in range(10):
        print("Hello, World!")  # Loop control variable is not needed.
    
    a, _ = (1, 2)  # Only the first value is needed.
    

    Each of these uses of underscore serves a different purpose in Python programming, making underscores highly versatile.

Leave an answer