Skip to main content

Understanding the usage of underscore( _ ) of Python for beginner. On Python Hunter





Introduction:
Just like you, a newbie in python scripting language, me too was confused about lot of new things in python that are not valid or available in other languages like Java, .Net etc.

Just like other things i had seen the use of '_' underscore in python, at beginning level that flabbergasted me for a while.



 Follow Python Hunter on youtube   Follow Python Hunter on twitter Follow on tumbl ( at your own risk ) check profile on linkedIn 



With some research and practice i have summarised the following usage of '_' underscore in python. Hope you will find it helpful at beginning level.


First Usage: Hold the previous output value. When used in interpreter.


1
2
3
4
5
6
7
_ = input() # For example you typed '5'

print(_)  # This will print '5'

print( int( _ ) * int( _ ) ) # This will print '25'

print( int( _ ) + 10 ) 

The above will print '15', because last input was "5" and in above line of code is producing '25' as output but not being handled by ' _ ' .

I had to convert _ to Integer with int(_) because input() method from python version 3.X takes everything as string.



Second Usage: Single leading '_' is to declare the variables, function, methods and classes in module as private.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
_privateVariable="" # private variable with single leading underscore.

class _privateClass:
    _itsPrivateVariable="PrivateValue"

    def _privateMethod(self):
        # print (_itsPrivateVari);
        # the above line will produce error as it is accessing
        # private var.

        print (_privateClass._privateVariable)

        print (self._itsPrivateVariable)

        # above two lines are two different methods to access the private var
        # CLASSNAME.PRIVATEVAR ...
        #           or
        # use the 'self' keyword

OBJ=_privateClass()
OBJ._privateMethod()

Third Usage: Single trailing '_' to avoid conflicts with python's inbuilt keywords.

1
2
3
4
5
6
7
class new:
    def class_(self):
        print("hello from class_")
        _list_=["private","LIST","With","Trailing","Underscore","to avoid","ambiguity"]

'''Private list variable with leading underscore declares it private
and trailing underscore resolves the conflict with reserved keyword 'list'.'''

Fourth Usage: For mangling the method names, just like in java overriding concept.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class A:
    def _parrot(self):
        print(" _parrot says HELLO!! ")

    def __dog(self):
        print(" __dog() of class A.")


class B(A): # class B is inheriting class A
    def __dog(self):
        print(" __dog() of class B.")


OBJ_A=A() # creating objects
OBJ_B=B() # creating objects
OBJ_A._parrot()
OBJ_A._A__dog()
OBJ_B._B__dog()
OBJ_B._A__dog()
what is actually happening here, in class A method __dog() is declared and class B method __dog() is declared, and there is absolutly no problem.
Problem is class B is child class A, means that class B will have access to class A's methods and variables i.e 
method _parrot() and __dog() .
The real mess is that how we, other developers or python will know with what object, which method to call?

OBJ_A._parrot() clearly defines that OBJ_A is object of class A and calling it's private method _parrot(), no doubt about it.

OBJ_A._A__dog(), OBJ_A is object of class A and calling it's mangled method __dog(), how can we be sure about it?
Pay little attention here, normally we call any method with objName.methodName(), here in this case we are calling __dog() method with concatenating _ClassName in front of __dog() method.

In OBJ_A._A__dog() the '_A' after dot(.) and before __dog() defines that this __dog() belongs to class A.

Hope the next two lines will provide a lucid vision of mangling.
         OBJ_B._B__dog() is calling __dog() method of class B.
         OBJ_B._A__dog() is calling __dog() method of class A.
In java this processing is called "overriding" in python we can say is "Mangling"
         Output:-
         _parrot says HELLO!! 
         __dog() of class A.
         __dog() of class B.

         __dog() of class A.

Fifth Usage: To create special methods.
This convention is used to create special variables or methods (so-called “magic method”) such as __init__, __len__. 
These methods provides special syntactic features or does special things. 
For example, __init__ works a constructor in a class.
A user of course can make custom special method, it is very rare case, but often might modify the some built-in special methods. 
But most experienced python developer recommend to avoid this convention to create your own special "magic methods".

Sixth Usage: To Ignoring values.

# Ignore a value when unpacking

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Ignore a value when unpacking

x, _ , y = (1, 2, 3) # x = 1, y = 3 

# Ignore the multiple values. It is called "Extended Unpacking" which is available in only Python 3.x

x, *_ , y = (1, 2, 3, 4, 5) # x = 1, y = 5  

# Ignore the index

for _ in range(10):
    do_something()  

# Ignore a value of specific location

for _, val in list_of_tuple:
    do_something()
I hope this blog will clear you confusions about the different usage of underscore '_' in python.
Your comments are valuable for this blog. And every one is invited to make valid corrections and make this blog helpful others.
Please do share your experiences and problems regarding this blog and its content, surly i will help you.

Thanks in anticipation.
Pran.

Comments

  1. Thank you so much for making this blog. I was searching for some beginner level python tutorial to clear my confusions and this is the one. It really helped a lot. Thank you so much Pran Sukh (Blogger) for your efforts.

    ReplyDelete
    Replies
    1. Thanks. M also a bigener in python... I'm not helping anybody, on the contrary we are helping each other.

      Delete
  2. Hi thanks for the blog.
    Being a beginner i am always in search for some helpful blogs.

    It really worked for me.
    Thanks Pran Sukh....

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Great post

    A little note:
    "Single leading '_' is to declare the variables, function, methods and classes in module as private."

    This is by convention, and is not enforced by the interpreter.

    ReplyDelete

Post a Comment

Thanks in anticipation.

Popular posts from this blog

Understanding "with" keyword in python, on Python Hunter

J ust like anything in python, keyword "with" is introduced in python to make the things little easy. Imagine a situation where you have to manage the resources e.g opening file and closing them after the code is executed on file. To achieve this sort of task we have to write the code as follow:      Download   But if you do it often you could do this as follow to make the code reusable: Download But why do you need to do this when you know that you have to execute the only for once.  To answer this question  python-dev team finally came up with following approach: Download  Note:- Make sure you have "file.txt" and python code file in same dir. The "with"  keyword replaces the try finally block. "with" keyword executes the openFileClass() context manager and internally calls the __enter__(self) method, and whatever is being returned from __enter__(self) method is being stored in tar

XML, XSLT info by pran sukh on Python Hunter blog.

What is XML? Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost. XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data. XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data. With XML, data can be available to all kinds of "reading machines" like people, computers, voice machines, news feeds, etc. XML:- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category= "cooking" > <title lang= "en" > Every