What is the meaning of single underscore prefix with Python variables?

In Python, a single underscore prefix (_variable) serves as a convention to indicate that a variable is intended for internal use. This is known as a "weak private" indicator that signals to other developers that the variable should be treated as an implementation detail.

Syntax

The syntax for single underscore prefix variables is ?

_variable_name

Single Underscore in Classes

When used in classes, single underscore variables are accessible but indicate internal use ?

class Python:
    def __init__(self):
        self.public_var = 37
        self._internal_var = 76

obj = Python()
print(obj.public_var)
print(obj._internal_var)  # Still accessible but indicates internal use
37
76

Module Import Behavior

The single underscore affects how variables are imported with from module import *. Let's create a module example ?

# File: my_module.py
def public_function():
    return "This is public"

def _internal_function():
    return "This is internal"

public_var = "Available"
_internal_var = "Not imported with *"

When importing with *, underscore-prefixed names are excluded ?

>>> from my_module import *
>>> public_function()
'This is public'
>>> _internal_function()
NameError: name '_internal_function' is not defined

However, explicit imports still work ?

>>> import my_module
>>> my_module._internal_function()
'This is internal'

Comparison with Double Underscore

Here's how single underscore differs from double underscore (name mangling) ?

class Example:
    def __init__(self):
        self._single = "Semi-private"
        self.__double = "Name mangled"

obj = Example()
print(obj._single)  # Accessible
print(obj.__double)  # This will cause an AttributeError
Semi-private
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no attribute '__double'

Best Practices

Convention Purpose Accessibility
variable Public Fully accessible
_variable Internal use Accessible but discouraged
__variable Name mangling Mangled, harder to access

Conclusion

Single underscore prefix is a Python convention indicating internal use. It doesn't enforce privacy but signals intent to other developers. Use it for variables meant for internal implementation details.

Updated on: 2026-03-24T19:43:48+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements