non-public name
In Python, a non-public name refers to the name of a variable, function, method, or attribute that is intended for internal use within a module or a class. These names are prefixed with an underscore (_
) to signal that you shouldn’t access or modify them directly from outside the module or class.
Python doesn’t enforce strict access restrictions. Using a leading underscore is a naming convention that communicates the intended use of certain elements.
By marking a name as non-public, you indicate that it’s an implementation detail that can affect the module or class’s external interface be changed with.
Example
Here’s an example of non-public names in a Python class:
class DemoClass:
def __init__(self, value):
self._hidden_value = value # Non-public attribute
def get_value(self):
return self._hidden_value
# Usage
demo = DemoClass(42)
demo.get_value() # Output: 42
# Don't do this
print(demo._hidden_value) # Outputs: 42
Related Resources
Tutorial
Single and Double Underscores in Python Names
In this tutorial, you'll learn a few Python naming conventions involving single and double underscores (_). You'll learn how to use this character to differentiate between public and non-public names in APIs, write safe classes for subclassing purposes, avoid name clashes, and more.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Single and Double Underscore Naming Conventions in Python (Course)
- Single and Double Underscores in Python Names (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)