Posts

Finally block always runs in python, avoid returning values in this block

>>> def foo(): ...    try: ...        return 1 ...    except: ...        return 2 ...    finally: ...        return 3 ...  >>> foo() 3 >>> def foo(): ...     try: ...        raise ValueError ...     except: ...        return 2 ...     finally: ...        return 3 ...  >>> foo() 3

Taking screen shot on chrome book

Image
To take a screenshot of the entire screen, press the ‘Ctrl’ and ‘Window Switcher’ keys at the same time: To capture some specific area of the the screen on chrome book, press the ' Ctrl' , 'Shift' and 'Window Switcher' combination at the same time On the newer versions of Chromebook you have the option for 'Take screenshot' under 'More tools' drop down in the Chrome Menu. A notification pops up and click on it would take you to the screenshot saved as .PNG under Downloads folder in the File Manager .

Avoid using global/class-level mutable datatypes like list/dicts

Class-level variables that are assigned with mutable datatypes are like global static variables, they refer to the same list or dict and can be modified/accessed via multiple instance or through the class itself, >>> class Foo: bar = [] >>> a, b = A(), A() >>> a.bar.append(10) >>> a.bar [10] >>> b.bar [10] >>> Foo.bar [10] >>> class A: def __init__(self): self.bar = [] >>> a, b = A(), A() >>> a.bar.append(10) >>> a.bar [10] >>> b.bar [] >>> Foo.bar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'Foo' has no attribute 'bar' To avoid using the same global list/dict across multiple instances we should avoid initializing class/global variables with a mutable datatypes like list/dict

How to restart networking without DHCP RELEASE on Ubuntu

On Ubuntu systems, there is no more networking service restart option, so users are forced to do ifdown and ifup. But  ifdow n  by default do a DHCPRELEASE causing systems to potentially change IPs on ifup. This would not be a very appreciated sideaffect with automated systems where IPs could change during the lifetime of the system. Following script allows you to restart networking without actually do a DHCPRELEASE, (to avoid the DHCPRELEASE create temporary interfaces with all interfaces set to static and  bring down interfaces using that file, but use the original file to do the bring up the interfaces) # cat ifdownup.sh pkill dhclient && \ sed 's/dhcp/manual/' /etc/network/interfaces > /tmp/interfaces && \ for intf in `cat /etc/network/interfaces | grep inet | cut -d ' ' -f 2`; \ do ifdown $intf -i /tmp/interfaces && ifup $intf; done​

Avoid initializing kwargs in signature as they might not work as expected when you need to pass kwargs from other methods

$ cat test_kwargs . py def m1 ( a , b = 2 ) : print a , b def m2 ( a , b = None ) : ​m1 ( a , b = b ) m1 ( 1 ) m2 ( 1 ) m1 ( 1 , 2 ) m2 ( 1 , 2 ) $ python test_kwargs . py 1 2 1 None 1 2 1 2 A better version of the above methods would be, ​ $ cat test_kwargs . py def m1 ( a , b = None ) : if b is None : b = 2 print a , b def m2 ( a , b = None ) : m1 ( a , b = b ) m1 ( 1 ) m2 ( 1 ) m1 ( 1 , 2 ) m2 ( 1 , 2 ) $ python test_kwargs . py 1 2 1 2 1 2 1 2​

Understanding multiple inheritance and method resolution order in Python

# cat multiple_inheritance.py import inspect class A ( object ): pass class B (A): pass class C (A): pass class D (B): pass class E (C): pass class F (D, E): pass print inspect.getmro(A) print inspect.getmro(B) print inspect.getmro(C) print inspect.getmro(D) print inspect.getmro(E) print inspect.getmro(F) # python multiple_inheritance.py (< class ' __main__ .A '>, <type ' object '>) (< class ' __main__ .B '>, <class ' __main__.A '>, <type ' object '>) (< class ' __main__ .C '>, <class ' __main__.A '>, <type ' object '>) (< class ' __main__ .D '>, <class ' __main__.B '>, <class ' __main__.A '>, <type ' object '>) (< class ' __main__ .E '>, <class ' __main__.C '>, <class ' __main__.A '>, <type ' object '>) (< class ...

In Perl keys get defined if they are accessed as hash, without checking for their existence

In the following code snippet, 'c' is not as key in 'foo' but is set to {} when the last check for foo->c->0 is called. / tmp ( ) $ cat foo . pl use strict ; use warnings ; use Data : : Dumper ; sub abcde { my $foo = { 'a' = > 1 , 'b' = > 2 } ; print Dumper ( $foo ) ; if ( exists $foo - > { c } & & defined $foo - > { c } - > { 0 } ) { print "C is defined" ; } print Dumper ( $foo ) ; if ( defined $foo - > { c } and defined $foo - > { c } - > { 0 } ) { print "C is defined" ; } print Dumper ( $foo ) ; if ( defined $foo - > { c } - > { 0 } ) { print "C is defined" ; } print Dumper ( $foo ) ; } abcde ( ) ; / tmp ( ) $ perl foo . pl $VAR1 = { 'a' = > 1 , 'b' = > 2 } ; $VAR1 = { 'a' = > 1 , ...

eventlet.GreenPool.waitall() just logs the exception but doesn't raise them

waitall() method in eventlet.GreenPool doesn't raise exceptions but just logs them, whereas in case of wait on the greenthread returned by spawn from evenlet.GreenPool raises the exception. # cat foo . py import eventlet pool = eventlet . GreenPool ( 1 ) def foo ( ) : raise ValueError gt = pool . spawn ( foo ) try: pool . waitall ( ) except Exception , e : print " pool.waitall Exception raised: %r " % e try: gt . wait ( ) except Exception , e : print " gt.wait() Exception raised: %r " % e # python foo . py Traceback ( most recent call last ) : File " /usr/lib/python2.7/site-packages/eventlet/hubs/hub.py " , line 346 , in fire_timers timer ( ) File " /usr/lib/python2.7/site-packages/eventlet/hubs/timer.py " , line 56 , in __call__ cb ( * args , * * kw ) File " /usr/lib/python2.7/site-packages/eventlet/greenthread.py " , line 194 , in main result = functi...

Using repr instead of str for parameters (not objects) for disambiguity

>>> for e in ( 0 , "0" , None , "None" , 1.23 , "1.23" , [ 1 , 2 ], { "foo" : "bar" }): ... print " %r " % e ... 0 '0' None 'None' 1.23 '1.23' [ 1 , 2 ] { 'foo' : 'bar' } When %s is used to interpolate to string there could be a bit of ambiguity introduced. >>> for e in ( 0 , "0" , None , "None" , 1.23 , "1.23" , [ 1 , 2 ], { "foo" : "bar" }): ... print " %s " % e ... 0 0 None None 1.23 1.23 [ 1 , 2 ] { 'foo' : 'bar' }

Redirect both stdout and stderr to dev null using > /dev/null 2>&1 for linux commands and scripts

/ tmp ( ) $ cat out_err_redirect_test . sh echo message to stdout echo message to stderr > & 2 / tmp ( ) $ bash out_err_redirect_test . sh message to stdout message to stderr # Message to stdout is redirected to dev null / tmp ( ) $ bash out_err_redirect_test . sh > / dev / null message to stderr # Message to stderr is redirected to dev null / tmp ( ) $ bash out_err_redirect_test . sh 2 > / dev / null message to stdout # Message to stderr and stdout is redirected to dev null / tmp ( ) $ bash out_err_redirect_test . sh > / dev / null 2 > / dev / null # Messaged to stdout is redirected to dev null , and stderr to configured stdout ( implies dev null ) / tmp ( ) $ bash out_err_redirect_test . sh > / dev / null 2 > & 1 # Message to stderr is redirected to stdout ( screen ) and stdout to dev null / tmp ( ) $ bash out_err_redirect_test . sh 2 > & 1 > / dev / null message to stderr

Tuples are expanded as multiple arguments when passed to print statement after %

Below the tuple (1, 2, 3) is getting expanded as 3 arguments and the format representation is expecting to have 3 %s or %r to be printed, > > > print " %r " % ( 1 , 2 , 3 ) Traceback ( most recent call last ) : File " <stdin> " , line 1 , in < module > TypeError: not all arguments converted during string formatting > > > print " %s " % ( 1 , 2 , 3 ) Traceback ( most recent call last ) : File " <stdin> " , line 1 , in < module > TypeError: not all arguments converted during string formatting > > > print " %s " % str ( ( 1 , 2 , 3 ) ) ( 1 , 2 , 3 )

Loop over an array with index and element in the array

Perl looping of an array with index as well as the item stored in variables, /tmp$ cat loop_with_index.pl  my @arr=(1,2,3,4); while (my ($i, $x) = each(@arr)) {     print "$i: $x\n"; } /tmp$ perl loop_with_index.pl  0: 1 1: 2 2: 3 3: 4

Perl constant hashrefs are actually functions

To get the keys of a constant hashref you first need to learn that a constant is actually a function and hence use () to get the keys from it INPUT: $ cat perlConstant.pl use Data::Dumper; use constant FOOHASH => { "foo" => "bar", }; print FOOHASH->{"foo"}."\n"; foreach $key (keys %{FOOHASH()}) { FOOHASH->{$key} = "bar1"; } print FOOHASH->{"foo"}."\n"; foreach $key (keys %{FOOHASH}) { FOOHASH->{$key} = "bar2"; } print FOOHASH->{"foo"}."\n"; OUTPUT: $ perl perlConstant.pl bar bar1 bar1

How to avoid adding duplicate keys to dictionary by mistake ...

There would be cases where large dictionaries are being embedded in the code (multiple pages in length) and users might append something to end of the dictionary, just assuming that its not already in the dictionary.  This could be easily avoided by following dict() instead of {} notation for dictionaries. > > > a = { . . . 'a' : 1 , . . . 'b' : 2 , . . . 'c' : 3 , . . . 'd' : 'nextpage' , . . . 'a' : 0 . . . } > > > print a { 'a' : 0 , 'c' : 3 , 'b' : 2 , 'd' : 'nextpage' } > > > a = dict ( . . . a = 1 , . . . b = 2 , . . . c = 3 , . . . d = 'nextpage' , . . . a = 0 . . . ) File " <stdin> " , line 6 SyntaxError : keyword argument repeated

Multiple repeat error when the regex has multiple wildcards in python re module

When the regex being compiled in python which has multiple wild cards like plus or asterisks sequentially repeated, you will need to escape or else run into "multiple repeat error". This can happen with any of re module methods like search and sub etc, where the regex is compiled. > > > import re > > > re . compile ( " r++ " ) Traceback ( most recent call last ) : File " <stdin> " , line 1 , in < module > File " /usr/lib/python2.7/re.py " , line 190 , in compile return _compile ( pattern , flags ) File " /usr/lib/python2.7/re.py " , line 242 , in _compile raise error , v # invalid expression sre_constants . error : multiple repeat > > > re . compile ( " r** " ) Traceback ( most recent call last ) : File " <stdin> " , line 1 , in < module > File " /usr/lib/python2.7/re.py " , line 190 , in compile return _...

Splitting python path using os.path module

Avoid using "/" at the end of the directory paths as they would generate empty filename when used with functions like os.path.split() > > > import os > > > os . path . split ( '/tmp/foo' ) ( '/tmp' , 'foo' ) > > > os . path . split ( '/tmp/foo/' ) ( '/tmp/foo' , '' ) Reference: https://docs.python.org/2/library/os.path.html

Class/Global variables vs Instance Variables ...

Class/Global variables are like CoW, only when the instances assign them values they have their own memory location allocated. For example in this case a.bar is assigned a value and hence it has different memory location allocated, but the same is not the case with b.bar >> > class Foo ( object ) : bar = None >> > repr ( Foo . bar ) 'None' >> > a = Foo ( ) >> > a . bar = 1 >> > repr ( Foo . bar ) 'None' >> > a . bar 1 >> > b = Foo ( ) >> > b . bar >> > repr ( b . bar ) 'None' >> > a . bar 1 >> > id ( Foo . bar ) 135796184 >> > id ( a . bar ) 151257264 >> > id ( b . bar ) 135796184

To speed up accessing files on nfs shares on a ubuntu machine ...

To enable nfs caching on ubuntu, sudo apt-get install cachefilesd sudo sed -i 's/nfs rw/nfs fsc,rw/' /etc/fstab service restart cachefilesd To use tmpfs instead of disk cache use this after making sure the runner has atleast 12G of memory, mount | grep fscache || mount -t tmpfs -o size=8192m tmpfs /fscache ls /fscache/disk0 || dd if=/dev/zero of=/fscache/disk0 bs=1M count=8191 sleep 15 ls /fscache/disk0 && echo 'y' | mkfs.ext4 /fscache/disk0 mount /fscache/disk0 /var/cache/fscache -t ext4 service cachefilesd restart

Weakref proxy is for instance only ...

Proxy cannot be created for basic datatypes like list, dict, str and int. Proxy can be create for class instances only. Also proxy cannot be created for proxy of another instance. >>> import weakref >>> a = 'str' >>> b = weakref.proxy(a) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: cannot create weak reference to 'str' object >>> a = 1 >>> b = weakref.proxy(a) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: cannot create weak reference to 'int' object >>> a = [] >>> b = weakref.proxy(a) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: cannot create weak reference to 'list' object >>> a = {} >>> b = weakref.proxy(a) Traceback (most recent call last):   File "<stdin>",...

Raising vs Reraising exceptions in python

>>> def foo(x): ...    raise Exception('%s is invalid input' % x) ... >>> try: ...     foo(1) ... except Exception, e: ...     raise e                          # RE-RAISING EXCEPTIONS ... Traceback (most recent call last):   File "<stdin>", line 4, in <module>    # LOSES foo Exception: 1 is invalid input >>> try: ...     foo(1) ... except Exception: ...     raise                             # RAISING EXCEPTIONS ... Traceback (most recent call last):   File "<stdin>", line 2, in <module>   File "<stdin>", line 2, in foo          # STORES foo too Exception: 1 is invalid input >>>