Thursday, December 07, 2017

Python : Common pitfalls


Join a list if and only if all values in the list are strings:
Code:

print ("running %s" % ' '.join(cmd))

Error:

Traceback (most recent call last):

  File "test.py", line 29, in <module>

    print ("running %s" % ' '.join(cmd))

TypeError: sequence item 4: expected string, int found


Cause:

There are non-strings in the list cmd.


Ex:

cmd = ["runthis.py", "--host", host, "--port", port]



To make join  happy:

cmd = ["runthis.py", "--host", host, "--port", str(port)]



Avoid default values in mutable arguments:

Code:

class A:

    def __init__(self, lst=[]):

        self.lst = lst



a = A()

b = A()

a.lst.append('crocs')


print (b.lst)


Output:

['crocs']


Cause:

Python evaluates default arguments to a function at the time the function
is defined, not each time it is called. So all instances will mutate a single 
list.

No comments: