Monday, February 9, 2015

Python traps

Short post today: I love Python. Unfortunately, like all programming languages, it has some traps that you might fall into if you don't pay attention. Read this blog post for more information.

For instance

def myMethod(lst=[]):
    lst += 'a'
    return lst

doesn't do what you think it does. Indeed:

> myMethod()
['a']
> myMethod()
['a', 'a']
> myMethod()
['a', 'a', 'a']

Suprise!
For once, C++ is more user-friendly, as it will create a new instance for the value of default parameters every time the method is called. That is not the case in Python.

No comments:

Post a Comment