Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Python Tips & Tricks»Understanding Python’s Underscore ( _ ): A Comprehensive Guide

    Understanding Python’s Underscore ( _ ): A Comprehensive Guide

    By RahulMay 27, 20233 Mins Read

    Python, as a flexible and intuitive language, introduces many constructs that enable the ease of coding. One such construct is the underscore ( _ ), a special character with multiple uses, ranging from variable naming to interpreter purposes, and more. For novice programmers, underscores might appear confusing, but understanding their purpose can significantly enhance your Python programming prowess. This article delves into an in-depth exploration of Python underscores, demystifying their diverse usages and significance.

    Advertisement

    Single Underscore

    1. As a Throwaway Variable
    2. Often in Python, we come across a situation where we need to iterate over a range or any iterable, but we don’t intend to use the variable inside the loop. In such scenarios, the single underscore is employed as a ‘throwaway’ variable, indicating that the loop variable is being intentionally ignored.

      1
      2
      for _ in range(5):
          print("Hello, Python!")

    3. After a Name
    4. In Python, a single underscore after a name is used as a naming convention to indicate a name is meant for internal use. It suggests that a variable, method, or attribute is intended for internal use within the class, module, or function, and it’s not part of the API.

      1
      2
      3
      4
      class MyClass:
          def __init__(self):
              self.public_var = "I'm public!"
              self._internal_var = "I'm internal!"

      Although Python doesn’t enforce privacy with these names, the underscore is a strong hint to the programmer that it’s intended for internal use.

    Double Underscore (Dunder)

    1. Before a Name
    2. When you see a name prefixed with double underscores ( __ ), it’s Python’s way of name mangling. This is primarily to avoid naming conflicts with names in subclasses. Python automatically prefixes the name with a class name.

      1
      2
      3
      class MyClass:
          def __init__(self):
              self.__private_var = "I'm very private!"

      Here, `__private_var` would be mangled to `_MyClass__private_var`, thereby avoiding any potential naming conflicts.

    3. Surrounding a Name (Magic Methods)
    4. Double underscores both before and after a name have a special meaning. These are associated with Python’s magic methods. These are special methods that you can define to add “magic” to your classes, like overloading operators or implementing protocol methods. Magic methods are an essential part of Python’s object-oriented features.

      1
      2
      3
      4
      5
      6
      class MagicClass:
          def __init__(self, num):
              self.num = num
       
          def __str__(self):
              return f"A MagicClass instance with number {self.num}"

      In the above code, `__str__` is a magic method that defines how the class should be converted to a string.

    Single Underscore in Interpreter

    In the Python interpreter, a single underscore has another interesting usage. It is used to hold the result of the last executed expression.

    1
    2
    3
    4
    >>> 5 + 5
    10
    >>> _
    10

    The _ gives the result of the last executed statement, i.e., 10 in this case.

    Double Underscore in Numeric Literals

    Python (from version 3.6 onward) also allows underscores in numeric literals. This is purely for enhancing readability for humans. For example, you could write one million as 1_000_000, and Python would interpret it as 1000000.

    1
    2
    3
    >>> num = 1_000_000
    >>> num
    1000000

    The underscore in numeric literals doesn’t affect the value; it’s just a readability feature.

    Conclusion

    Underscores in Python are far from an insignificant detail. They have well-defined purposes, depending on their placement and quantity. Understanding the usage of underscores can not only help make your code cleaner and more idiomatic but also lead you toward harnessing Python’s full potential. Happy Pythoning!

    Operator Python Underscore
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Python Function with Parameters, Return and Data Types

    An In-depth Guide to Using the =~ Operator in Bash

    How to Use Python with MySQL for Web Development

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Setting Up Angular on Ubuntu: Step-by-Step Guide
    • Converting UTC Date and Time to Local Time in Linux
    • Git Restore: Functionality and Practical Examples
    • Git Switch: Functionality and Practical Examples
    • Git Switch vs. Checkout: A Detailed Comparison with Examples
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.