Labels

Tuesday 1 January 2013

Python Tricks

What is 'if __name__ == "__main__"' for?

Basically  __name__ is a built-in variable which help to self identify whether the program is running as standalone or it has been imported into some other programs. If it is run as standalone then __name__ variable would be assigned with value of __main__, otherwise not.

For example, create two files one.py and two.py as mentioned below. When you run the one.py from the command line, it prints 'aa' as the __name__ would have the value __main__. But it will be different when you run the two.py script which has imported the one.py:
one.py file has following code:
if __name__ == '__main__':

    print ('aa')
else:
    print ('bbb')

two.py has below code:
import one

Run the-- python two.py:
Output will be: 
>>> 
bbb

Run the-- python one.py:
>>> 
aa

How to implement arbitrary arguments in python? 
*args in a function declaration would help to accept and retrieve arbitrary number of arguments. For example:

create the following code and run it:

def argu(*args):
    #print(arg)
    print (args)
    for arg in args:
        print(arg)
    
argu(1,2,3,"test")

Output would be like this
(1,2,3,"test")
1
2
3
test

Similarly, **kwargs accepts arbitrary number of dictionary elements:
For example,

def argu(**kwargs):
    #print(arg)
    print (kwargs)
    for arg in kwargs:
        print(arg)
argu(one=1,two=2)   

And output would be something like this:
{'two': 2, 'one': 1}
two
one

And even if you don't pass any arguments (for example, call the function as argu()), the script still execute well.

No comments:

Post a Comment