What Does _ Or __ Means In Python

Underscore _ or double underscore __ has special meanings in Python programming. This article will give you some examples to tell you what is the exact meaning of _ and __ in different scenario.

1. Use Single Underscore _ In Python Interpreter.

In Python interpreter, single underscore _ means the last expression value. The value can be any data type, number, string, even Django QuerySet.

# _ value is an integer.
>>> 10
10
>>> _
10
>>> _ * 5
50

# _ value is a string
>>>'hello'
'hello'
>>>_
'hello'

# in below example _ value is an Django QuerySet object.
>>> from dept_emp.models import Department, Employee
>>> from django.contrib.auth.models import User
>>> emp = Employee.objects.filter(user__username='tom')
>>> emp
<QuerySet [<Employee: tom,10000,13901234568>]>
>>> _
<QuerySet [<Employee: tom,10000,13901234568>]>

2. Use Single _ To Ignore Values.

You can use single _ to ignore values which you do not need to care or save, this can make your source code simple.

  1. Ignore tuple value when unpacking the tuple.
    >>> x, _, y = ('a', 2, 'c')
    >>> x
    'a'
    >>> y
    'c'
  2. Ignore more values in a tuple when unpacking it.
    >>> x, *_, y = ('a', 6, 8, 2, 5) 
    >>> x
    'a'
    >>> y
    5
  3. Ignore index in a loop.
    >>> for _ in range(10):     
    ...     print(_)
    ...     
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

3. Use Single _ To Define Private Class, Variable, Function or Method.

  1. If you add single _ in front of a class, variable or method definition then it means this class, variable or method is private. But in python the private is not real private, it just tell you it is private but you can still call it in other class. For example, we define two classes _ClassA and ClassB in test1.py and define ClassC in test2.py as below. So _ClassA and ClassB ‘s python module name is test1 (python file name). ClassC‘s python module name is test2.
  2. test1.py

    _a = 10
    
    
    class _ClassA:
         _a = 100
         
         b = 80
                 
                 
    class ClassB:
        
        x = 100
        
        def _show_class_a_variable(self):
       
            print('ClassB ' + str(_ClassA._a))
        
            print('ClassB ' + str(_ClassA.b))             
    
    if __name__ == '__main__':
        print(_a)
        
        print(_ClassA._a)
        
        print(_ClassA.b)
        
        cls_b = ClassB()
        
        cls_b._show_class_a_variable()
  3. test2.py

    from com.dev2qa.example.underscore.test1 import _ClassA, ClassB
     
    class ClassC:
        
        desc = 'This is class c.'
        
        def _show_class_a_variable(self):
       
            print('ClassC ' + str(_ClassA._a))
        
            print('ClassC ' + str(_ClassA.b))
            
            print('*********************************')
            
            cls_b = ClassB()
            
            cls_b._show_class_a_variable()
        
                 
    
    if __name__ == '__main__':
        
        _cls_a = _ClassA()
        
        print('ClassA _a = ' + str(_cls_a._a))
        
        print('ClassA b = ' + str(_cls_a.b))
        
        print('*********************************')
        
        cls_c = ClassC()
        
        print(cls_c.desc)
        
        print('*********************************')
        
        print(cls_c._show_class_a_variable())
  4. When you execute above python file, you can get below output result.
    ClassA _a = 100
    ClassA b = 80
    *********************************
    This is class c.
    *********************************
    ClassC 100
    ClassC 80
    *********************************
    ClassB 100
    ClassB 80

4. Use Single _ To Avoid Python KeyWord Conflict.

If you define a variable with name class or list, this will conflict with the python keyword. So you can add _ at the end of the keyword (class_, list_ ) to distinguish your variable name from the python keyword.

5. Use Double _ Both At Beginning And End Of Variable.

This means the method or variable is a special method.

  1. __file__ : Return the python file’s location path.
  2. __init__ : This method will be executed when python class’s instance is initialized for the first time.

6. Use Double _ In Django Filter Function.

  1. The double _ ( __ )  in Django filter method is lookup separater. For example.
    Below is the Django Department model class definition.

    class Department(models.Model):
        dept_name = models.CharField(max_length=1000)
        dept_desc = models.CharField(max_length=1000)

    Below code will filter out all Departments that dept_name contains ‘D’.

    >>> from dept_emp.models import Department
    >>> Department.objects.filter(dept_name__contains='D')
    <QuerySet [<Department: Develop,Develop web site use Python Django>, <Department: defence,defence department>]
  2. The double underscore __ is used as the foreign key model attribute separater. Below Employee model class has a foreign key user, and the foreign key user is an instance of django.contrib.auth.models.User, so we can use user__username in the filter method to execute the query.
    >>> from dept_emp.models import Employee
    >>> from django.contrib.auth.models import User
    # the Employee class's user attribute is a foreign key of django.contrib.auth.models.User object.
    >>> Employee.objects.filter(user__username='tom')
    <QuerySet [<Employee: tom,10000,13901234568>]>

References

  1.  What Does Double Underscore ( __ ) Means In Django Model QuerySet Objects Filter Method
  2.  How To Operate Foreign Key And Many To Many Field In Django Model

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.