Like every language, there are some easy to overlook traps when writing Python programs. Some of the traps are hidden and can cause big problems or errors for your program. Here are some of the most common traps a good Python programmer should be aware:
- 1. a mutable object used as the default parameter
Like all the other languages, Python provides default parameters for functions which are great for making thing easier. However, things can become unpleasant if you have put a mutable object in the function as the default value for a parameter. Let’s look at an example:
A surprise? ! The root cause is that everything is an object in Python, even function and default parameter is just an attribute of the function. Default parameter values are evaluated when the function definition is executed.
Another more obvious example:
How to fix it?
According to Python document: A way around this is to use None as the default, and explicitly test for it in the body of the function.
- 2. x += y vs x = x+y
Generally speaking, the two are equivalent. Let’s look at the example:
As we can see, when using +=, it returns the same id. In the first example (53,54), x points to a new object while the latter one (55,56) it modifies its value at the current location.
- 3. Majic parathesis ()
In Python, () can represent a tuple data structure which is immutable.
What if you only have one element in the tuple:
Majic, it becomes an integer instead of a tuple. The right thing to do is this:
- 4. Generated element is a list of list
This is like a 2-D array. Or generating a list with mutable element in it. Sounds very easy:
By adding a value 10 into the first element in the list, we populated all the elements with the same value. Interesting, hmmm? That’s not what I want!!
The reason is still the same: mutable object within the list and they all point to the same object. The right syntax is:
As seen above, there are many traps while using Python and definitely you should be aware of it.