I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a function, a method, etc?
Join Stack Overflow to learn, share knowledge, and build your career.
|
Single UnderscoreNames, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself. To quote PEP-8:
Double Underscore (Name Mangling)From the Python docs:
And a warning from the same page:
Example
|
|||||||||||||||||||||
|
|
Excellent answers so far but some tidbits are missing. A single leading underscore isn't exactly just a convention: if you use The leading-underscore convention is widely used not just for private names, but also for what C++ would call protected ones -- for example, names of methods that are fully intended to be overridden by subclasses (even ones that have to be overridden since in the base class they For example, to make a thread-safe queue with a different queueing discipline than FIFO, one imports Queue, subclasses Queue.Queue, and overrides such methods as |
|||||
|
|
No other form of underscores have meaning in the Python world. There's no difference between class, variable, global, etc in these conventions. |
|||||||||||||
|
|
You can still access Example:
t._b is accessible because it is only hidden by convention
t.__a isn't found because it no longer exists due to namemangling
By accessing |
|||||||||||||
|
|
Single underscore at the beginning: Python doesn't have real private methods, so one underscore at the start of a method or attribute name means you shouldn't access this method, because it's not part of the API.
code snippet taken from django source code (django/forms/forms.py). This means errors is a property, and it's part of the module, but the method this property calls, _get_errors, is "private", so you shouldn't access it. Two underscores at the beginning: This causes a lot of confusion. It should not be used to create a private method. It should be used to avoid your method to be overridden by a subclass or accessed accidentally. Let's see an example:
Output:
Now create a subclass B and do customization for __test method
Output will be....
As we have seen, A.test() didn't call B.__test() methods, as we might expect. But in fact, this is the correct behavior for __. So when you create a method starting with __ it means that you don't want to anyone to be able to override it, it will be accessible only from inside the own class. Two underscores at the beginning and at the end: When we see a method like
There is always an operator or native function which calls these magic methods. Sometimes it's just a hook python calls in specific situations. For example Let's take an example...
For more details PEP-8 guide will help more. Please find more magic methods in python here. https://github.com/RafeKettler/magicmethods/blob/master/magicmethods.pdf |
||||
|
|
|
Sometimes you have what appears to be a tuple with a leading underscore as in
In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the imports
and in sphinx.locale, _() is assigned as an alias of some localization function. |
||||
|
|
|
If one really wants to make a variable read-only, IMHO the best way would be to use property() with only getter passed to it. With property() we can have complete control over the data.
I understand that OP asked a little different question but since I found another question asking for 'how to set private variables' marked duplicate with this one, I thought of adding this additional info here. |
||||
|
|
|
Single leading underscores is a convention. there is no difference from the interpreter's point of view if whether names starts with a single underscore or not. Double leading and trailing underscores are used for built-in methods, such as Double leading underscores w/o trailing counterparts are a convention too, however, the class methods will be mangled by the interpreter. For variables or basic function names no difference exists. |
|||
|
|
|
Your question is good, it is not only about methods. Functions and objects in modules are commonly prefixed with one underscore as well, and can be prefixed by two. But __double_underscore names are not name-mangled in modules, for example. What happens is that names beginning with one (or more) underscores are not imported if you import all from a module (from module import *), nor are the names shown in help(module). |
|||||
|
|
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice. reference https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references |
|||||
|
|
Here is a simple illustrative example on how double underscore properties can affect an inherited class. So with the following setup:
if you then create a child instance in the python REPL, you will see the below
This may be obvious to some, but it caught me off guard in a much more complex environment |
||||
|
|
|
Getting the facts of _ and __ is pretty easy; the other answers express them pretty well. The usage is much harder to determine. This is how I see it:
Should be used to indicate that a function is not for public use as for example an API. This and the import restriction make it behave much like
Should be used to avoid name collision in the inheritace hirarchy and to avoid latebinding. Much like private in c#. ==> If you want to indicate that something is not for public use, but it should act like This is also a quote that I like very much:
But the problem with that is in my opinion that if there's no IDE that warns you when you override methods, finding the error might take you a while if you have accidentially overriden a method from a base-class. |
||||
|
|
protected by cᴏʟᴅsᴘᴇᴇᴅ Aug 23 '17 at 8:56
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?