What is the meaning of single and double underscore before an object name?

Cover Image for What is the meaning of single and double underscore before an object name?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

The Magic Behind Single and Double Underscores in Python 🎩✨

If you've been coding in Python for a while, you might have come across code that uses single or double underscores before an object's name. At first glance, these underscores might seem like random decorations, but they actually have a special meaning in Python.

The Mystery of the Single Underscore (_)

When it comes to using a single underscore before an object's name, there are two common scenarios:

1. Ignoring a Variable

Sometimes, you might need to assign a value to a variable, but you have no intention of using that variable later in your code. In such cases, using a single underscore is a Pythonic way to indicate that the variable is irrelevant.

name = "John"
_ = calculate_age(1990)

By convention, using a single underscore tells other developers that the variable can be ignored and is not expected to be referenced again.

2. Storing the Result of the Last Expression in a Python Shell

When you use Python interactively in a shell or a REPL (Read-Eval-Print Loop), a single underscore represents the result of the last expression you executed. It's like a handy memory bank that allows you to access previous results without explicitly assigning them to a variable.

>>> 3 + 5
8
>>> _ * 2
16

Using a single underscore in this context is a convenient way to refer to the previous result without having to type out the actual value.

The Enigma of the Double Underscore (__)

Now let's move on to the more intriguing topic of the double underscore before an object's name. This convention, also known as name mangling, has a specific purpose when used within class definitions.

Whenever you create a variable or a method with double underscores as a prefix, Python automatically adds a class-specific prefix to the name to avoid naming conflicts between different classes.

Here's a simple example to illustrate name mangling in action:

class MyClass:
    def __init__(self):
        self.__private_variable = 42

my_object = MyClass()
print(my_object.__private_variable)

🔍 When you run this code, you'll encounter an AttributeError. That's because the double underscore prefix causes Python to "mangle" the variable name, making it inaccessible from outside the class.

To access the mangled variable, you need to use the modified name, which combines the class name and the original variable name:

print(my_object._MyClass__private_variable)

While this name mangling feature can be useful in certain cases, it's important to remember that it is primarily intended for internal class usage. In general, it's considered good practice to respect the naming conventions and not try to access mangled variables directly from outside the class.

A Call-to-Action: Share Your Pythonic Experiences! 🐍🚀

Now that you've unraveled the mysteries behind single and double underscores in Python, it's time to apply this knowledge in your own code.

🔹 Have you come across any situations where you found the use of single or double underscores particularly helpful?

🔹 What are your thoughts on the name mangling technique? Have you ever encountered any pitfalls when using it?

🔹 Feel free to share your thoughts, experiences, or any related tips and tricks in the comments below. Let's ignite a Pythonic discussion! 💬✨

Remember, understanding and embracing these Pythonic conventions will not only make your code more readable but will also help you collaborate more effectively with other Python developers.

Happy coding! 💻🐍


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello