Tuesday, 21 April 2015

Python tips




1. Diffrence between  my_dict['key'] and my_dict.get() method

Dictionaries can be accessed by my_dict['key'] and get() method, both seems to do the exact same thing. 

With bracket syntax, an invalid key, a missing value etc, results in an exception being raised.

The get() method checks to see whether the provided key is present in the dictionary; if it is, the associated value is returned. If the key isn’t in the dictionary, an alternate value is returned instead. By default, the alternate value is None. You can pass a second arguement to override this default.

2. if __name__ == "__main__" : main()

Before executing a source file, python interpreter define few special variables. If interpreter is running a source file directly, it sets the value of __name__   as '__main__'. If it is imported, module's name will be set to '__name__'.

When you do the main check,  code only execute when you want to run the module as a program and it wont execute when somebody is importing it.

3. *args and **kwargs?

The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:

>>> def print_everything(*args):
        for count, thing in enumerate(args):
...         print '{0}. {1}'.format(count, thing)
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage

Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:

>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print '{0} = {1}'.format(name, value)
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:

def table_things(titlestring, **kwargs)

You can also use both in the same function definition but *args must occur before **kwargs.

You can also use the * and ** syntax when calling a function. For example:

>>> def print_three_things(a, b, c):
...     print 'a = {0}, b = {1}, c = {2}'.format(a,b,c)
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat

As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call. 


source(credit ) : http://stackoverflow.com/questions/3394835/args-and-kwargs

No comments:

Post a Comment