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=[]):
bad_list.append(3)
print bad_list
def gotcha_again(bad_list=[]):
bad_list = bad_list + [3]
print bad_list

print "calling gotcha_again"
gotcha_again()
gotcha_again()
print "calling gotcha"
gotcha()
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
[3]
[3]
calling gotcha
[3]
[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

list.sort()

sorted(list)

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…)

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.