Python gotcha

While browsing for some of the python “gotcha” I realized that everyone has the list gotcha but in my opinion that is always incomplete Consider this code

def gotcha(bad_list=[]):
print bad_list
def gotcha_again(bad_list=[]):
bad_list = bad_list + [3]
print bad_list

print "calling gotcha_again"
print "calling gotcha"

What happens when you call these two functions twice ?

If you have read the gotcha and applied it without understanding the reason, then you might expect both answers to be same.

However they would print :
calling gotcha_again
calling gotcha
[3, 3]

The reason has to with the inconsistency in the python language core( again my opinion). Python language is confused (although less than c++) b/w functional and OO and procedural language. Sometimes it would follow the “purity” concept of the functional languages and sometime it would completely violates it.

One other example of this conflict is



Why do you need two behavior for sorting list ?

…. May be for creating an interview question ;)…

Why should anyone care about consistency.

…It creates “well behaved” product..
While developing a framework I realized this fact the hard way. If all the functions have similar behavior then the need to go through the documentation for each functions is reduced considerably. You can make valid and reasonable assumptions about even those parts of codes which you have not thoroughly studied.

Example.. now if someone is not expert in python then because of this sorting irregularity he/she can never be sure if any function on list would change the input list or would return some value. You have to confirm it always (Not that confirming is bad but still…)