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

regex in python python hunter

Regular Expressions is a powerful concept if understood clearly you can save your valuable time to extract out the particular text from huge string or paragraph. It is wildly pronounced as regex, it can help you to automate the boring stuff, like searching particular text form log files, python used this same concept in web scrapping. Below are some common examples to understand the regex. Method names will help you to have an idea that what exactly the regex is intended to do. if you don't understand any regex or want to create your own regex with your requirements then you can comment below, i'll reach you ASAP. Thanks. import re def phoneNumberPattern (): print ( "*" * 10 ) print ( "phoneNumberPattern()" ) regexObj = re . compile( r'\d\d\d-\d\d\d-\d\d\d\d' ) mo = regexObj . search( 'Find my phone number from this string 998-805-4332' ) print (mo . group()) def grouping (): print ( "*...

XSLT applyTemeplate tag by pran sukh on Python Hunter.

XSLT is used for presenting XML data in well structured way and in eye appealing sense. In XSLT we can define different templates and maintain criteria for XSLT processor to parse the XML data in and apply different template for different XML tags. Lets examine following example XML DATA. 1 2 3 4 5 6 7 8 9 10 <student id= "1" eCode= "e1" > <firstName> Python 1 </firstName> <lastName> Hunert 1 </lastName> <dob> <day> 01 </day> <month> Jan </month> <year> 1991 </year> </dob> <course> Programmer </course> </student> In above XML data we want to present student id with dark background and eCode with red background colors, First Name in blue color, last name in green color and date of birth in different modes, so it will look like this. Source File:- XML_DATA.xml 1 2 3 4 5 6 7 8 9 10 ...