본문 바로가기
Python

[Python] Underscore Usage

by llHoYall 2021. 4. 26.

I'll post about the underscore(_) in Python.

Basic Usage

Previous Value

If you use underscore in REPL, it points to the previous result.

>>> 3 + 5
8
>>> _
8
>>> _ + 7
15

Ignoring Value

You can use underscore for ignoring values.

a, _, b = (1, 2, 3)
print(f"{a}, {b}")
# 1, 3

a, *_, b = (1, 2, 3, 4, 5, 6, 7)
print(f"{a}, {b}")
# 1, 7

If you use underscore in a loop, it indicates the current value itself as well as its use to ignore it.

for _ in range(3):
    print(_)
# 0
# 1
# 2

for _ in ['apple', 'banana', 'cherry']:
    print(_)
# apple
# banana
# cherry

Separating Digit

The underscore can be used to separate digits for readability.

binary = 0b_0010_0110
print(binary)
# 38

octal = 0o_0073
print(octal)
# 59

decimal = 1_231_210
print(decimal)
# 1231210

hexa = 0x_001a
print(hexa)
# 26

Single Pre-Underscore for Naming

You can add an underscore to the name of a variable or function.

#--- test.py ---#
_global_var = 'global'

class Test:
    def __init__(self):
        self._member_var = 'member'


#--- main.py ---#
from test import *

print(_global_var)
# Error: Not defined 

test_obj = Test()
print(test_obj._member_var)
# member


#--- main.py ---#
import test

print(test._global_var)
# global

test_obj = test.Test()
print(test_obj._member_var)
# member

It can protect not to expose in file scope, but it can not protect not to expose in class scope.

But there is a way to avoid this like the below case.

Single Post-Underscore for Naming

Actually, it is nothing special.

However, it can help to use a Python keyword as a name of a variable or function.

class = 3
print(class)
# Error: Invalid syntax

class_ = 7
print(class_)
# 7

Double Pre-Underscore for Naming

#--- test.py ---#
__global_var = 'global'

class Test:
    def __init__(self):
        self.__member_var = 'member'

    def get_var(self):
        return self.__member_var


#--- main.py ---#
from test import *

print(__global_var)
# Error: Not defined 

test_obj = Test()
print(test_obj.__member_var)
# Error: Doesn't have attribute
print(test_obj.get_var())
# member

Python works with name mangling if you use double pre-underscore to the name of a variable or function.

Therefore, you can hide them differently from a single pre-underscore case.

Double Pre and Post-Underscore for Naming

This is called as magic method or dunder method in Python.

You must have seen this in something like a constructor(__init__).

You can also use your own name of a variable or function.

#--- test.py ---#
__global_var__ = 'global'

class Test:
    def __init__(self):
        self.__member_var__ = 'member'
        
        
#--- main.py ---#
from test import *

print(__global_var__)
# Error: Not defined 

test_obj = Test()
print(test_obj.__member_var__)
# member


#--- main.py ---#
import test


print(test.__global_var__)
# Error: Doesn't have attribute 

test_obj = test.Test()
print(test_obj.__member_var__)
# member

'Python' 카테고리의 다른 글

[Python] defaultdict in collections  (0) 2021.05.01
[Python] deque in collections  (0) 2021.04.30
[Flask] Using Markdown on Flask  (0) 2021.03.01
[Flask] Send Email on Flask using Flask-Mail  (0) 2021.02.28
Draw Graph with MatPlotLib in Python  (0) 2021.02.25

댓글