views:

307

answers:

12

Possible Duplicate:
Common pitfalls in Python

Hello all,

inspired by this question Fastest way to learn Python? I've read the Dive into Python 3 webpage. I learned the basics, wrote a few simple programs and started to like the language. However i also started running into bugs, i did things wrong and my programs did not work as i wanted (google and SO helped me a lot to resolve these).

Now i would like to learn how to write good Python code. But wait, thats not my question! I realize that "good Python code" is something highly subjective and even worse, one cannot "learn" this knowing just the basics and having practicaly no real experience with the language. So instead i want to know, what should i NEVER do. So, what are the pitfals of Python? ( pytfals? :) ).

They say C lets you shoot yourself in the foot (and oh boy is that true!). Will Python bite me, if i let him?

+5  A: 

Never do this:

l = ['a', 'b', 'c']
result = ''
for i in l:
    result += i

instead:

''.join(['a', 'b', 'c'])

And never use from <module> import *.

Oh, and one more thing. Beware of catching all exceptions:

try:
  # something
except:
  # do something else

as this might catch you even SyntaxError :-)

Read Zen of Python :-)

And this can be helpful: http://www.siafoo.net/article/52

gruszczy
catch all is especially dangerous in python because it will also catch a KeyboardInterrupt.
carl
perhaps you mean 'except:' in lieu of 'catch:'?
pduel
Yeah, except ;-)
gruszczy
+1  A: 

Be aware of this behaviour, for instance.

sm
+2  A: 

This isn't directly related to the language, but BEWARE of copying and pasting Python code from one text editor/IDE to another. Some editors will reformat you code with respect to white space (replacing tabs/spaces and such). This can take a working piece of code and ruin it. If you are not aware of this pitfall then you can waste a lot of time.

My personal anecdote: I took a class in college and we had to do a project in Python. The professor provided some supporting code for the project to get us started. Many of my classmates copied his code off the website, pasted it into their editor, and then screamed the next class day about it now working. I was lucky enough to have had some Python experience and knew what was happening, but many lost a whole weekend's worth of working hours because they thought the professor's code was broken. (I realize that they should have contacted the professor immediately about the non-working code and not waited until the next class meeting. Any lost time was largely their fault)

wshato
Yep, had to use some intense sed to fix a whitespace issue caused by this.Also useful to know: when developing on a multiplatform team, SVN has a eol conversion tool... set it to native =)
JGord
+4  A: 

Learn the distinctions between the following statements:

x = [1, 2, 3, 4]
y = x
z = x

y[2] = 'HELLO'
print x  # prints [1, 2, 'HELLO', 4]

z = [3, 2, 1]
print x  # prints [1, 2, 'HELLO', 4]

Notice how when I modified y, it also modified x. However, when I assigned a new list into z, it didn't copy the new list into x, it gave it a new object.

Also, watch out for this in default parameters:

def default_list(x, mylist = []):
    mylist.append(3)
    print mylist     # this will print [3, 3, 3, 3, 3, 3...] (once per call)

In this case, mylist is only initialized once, not every time you call the function. Therefore, you want to instead do:

def default_list(x, mylist = None):
    if mylist is None:
        mylist = []
orangeoctopus
A: 

make sure (e.g. via pylint) you don't have a typo at the end of your code (preferably after a lot of lengthy computations) that results in an error a compiler would've found. it's not style exactly, but you're going to hate python for it and it's gonna be counterproductive ;)

Nicolas78
A: 

Python gives you a lot of tools in your arsenal--metaclasses, decorators, descriptors, self.__dict__, operator overloading, examining the execution frame, and lots more.

The most important thing I've had to learn is: don't use them.

At least, not all at once, and not without very good reasons to. Because Python gives you all this power, there's a tendency to come up with complicated solutions when there's simpler, more straightforward solutions available.

Python is a elegant, simple, and (dare I say) beautiful language that has a lot of flexibility and a lot of power. But there's often a tradeoff between power and simplicity--weigh that tradeoff carefully before you use a new feature.

Chris B.
+1  A: 
>>> x = [1]
>>> def test(x):
...     x = [2]
... 
>>> test(x)
>>> x
[1]

x is assigned as list but instead of using x.clear() and x.append() - x is being redeclared with diff. memory allocation.......

Tumbleweed
+1  A: 

Always, always, always use 'self'. Don't rename it 'this' (common for ex-Java programmers) or 'my' or anything else. Yes, your code will still run, but some other developers will be very unhappy with you.

Also, even though Python provides a lot of powerful built-in tools, the plethora of extensions and modules available online are even more useful. Anytime things get too complicated, there's probably a way to simplify your code from what oth ers have done. (Eg: don't nest list comprehensions four levels deep; instead, look up something like NumPy).

thebackhand
A: 

Ending lines with semicolons. It doesn't produce a compiler error, but Perl, Java etc. got me into the habit.

krs1
A: 

I wouldn't call this an avoidance aspect, but you will need to know your scopes and reference semantics.

Paul Nathan
A: 

Don't forget that Python is not Java. So no getters and setters and no class methods.

Dave Webb
Thanks of quoting my quote.
Tony Veijalainen
Just to clarify, all of those things are possible to do in Python. The point of the linked article is just don't do them unless it's necessary.
Peter Milley
A: 
string=input("write you code")
list= list(string)

And after this you are going to be very confused of what is wrong!

Tony Veijalainen
Good beginner tip: you should always used `raw_input` instead of `input` for getting user input.
orangeoctopus
lol never use keywords as varibles - else it will replace your keywords, never forget its not java or C# :D, and don't even think its pitfall of python its power of python :)
Tumbleweed