Double underscore vs single underscore before Python method

dEybid report abuse

What is the meaning of double leading underscore (_) and single leading underscore () before the Python method in a class? For example:

class A: def singleunderscored_method(): pass

def __double_underscored_method():
  pass

Answers

CarlosCV report abuse

Hi @dEybid

Single leading underscore means that the method is for internal use inside method only. Also, if you will perform such import:

from A import *

This wouldn't import methods with the leading underscore. Nevertheless, if you need to use this method, you can import it explicitly and use. But it is not a good habit. In other words, a single underscore is like a caution that this method is internal and should be used only inside the class.

Double underscore is a stronger indicator that the method should be used only inside the given class. Double underscore performs so-called name mangling. To call such a method you will need to use a weird construction:

A._A__double_underscored_method()
JuanG report abuse

Hi,

Single leading underscore is used to define an internal method, while double underscores - to define a private method. My recommendation is to avoid using private methods. When you want to show that this method shouldn't be used outside, just mark it as internal. Private methods could cause a lot of unexpected nasty things, especially if your program becomes complex, and when many programmers work together to develop it.

Regards.

Mike1191 report abuse

Maybe you will be interested in this material about how underscores are used in Python: https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc

Spoiler: It is not only for internal and private methods definitions, there are also many other interesting cases.

dEybid report abuse

Wow, it is very interesting! Thank you all!

Add Answer

Need support?

Just drop us an email to ... Show more