Mistakes that I — a new developer USUALLY makes when coding in python (part 2)

Vu Quang Hoa
1 min readMay 27, 2016

--

Part 1: Common mistakes

Function

1.Using a mutable value as a default value

def test(numbers=[]):
numbers.append(10)
print numbers
>>> test()
[10]
>>> test(numbers=[1,2])
[1, 2, 10]
>>> test(numbers=[1,2,3])
[1, 2, 3, 10]
# Now look carefully.>>> test()
[10] # intended
>>> test()
[10, 10] # Oops
>>> test()
[10, 10, 10] # What is that?
>>> test()
[10, 10, 10, 10] # Boom...

So what’s happening here?

Our thinking:
- if there is no argument, then 10 will be added to an empty list

In reality:
- Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well. (http://docs.python-guide.org/en/latest/writing/gotchas/)

=> Solution

def test(numbers=None):
if numbers is None:
numbers = []
numbers.append(10)
print numbers

Reference:

  1. https://www.toptal.com/python/top-10-mistakes-that-python-programmers-make
  2. http://docs.python-guide.org/en/latest/writing/gotchas/

3. http://blog.amir.rachum.com/blog/2013/07/06/python-common-newbie-mistakes-part-1/

--

--