When starting with Python or just when you haven’t read PEP 8 you usually fall into some frequent mistakes. Mostly because you take your experience in other languages to Python and your mind gets confused with the new conventions (or something like that).
Some of these errors and their explanation:
- if a == None:
Really common. None is a singleton, so you can (well, actually, have) to compare to it like ‘if a is None‘ or ‘if a is not None‘. - if (condition):
This is not really pythonic, if doesn’t take () around the condition in python, () purpose is grouping, you can use them in an if but only to clarify a really complex condition or similar stuff. Please don’t clutter code with unneeded characters. - if len(list):
This is a misunderstanding of Python way of things, any empty sequence (string, list, tuple) is False. So if you want to make sure a list is empty, just check if it’s False. Same for tuples, and in some ocassions for strings. - if type(obj) is type(1):
This is killing kittens, there’s a builtin function for this purpose, it’s called -surprise- isinstance(object, type). For example isinstance(123, int)
Read more about this and other conventions in PEP 8.
Tags: faq, programming, python, tips

I think you mean “isinstance(object, type)”, instead of “instanceof(object, type)”.
yes, thanks
Can you explain the first one?
You can use isinstance like this: instance(a,(int,float)) to test if a is one of a list of types.
Still have the instance function wrong. Its “isinstance(object, type)”, you just have “instance”.
Nice list though.
I don’t see the problem… these examples lack style but none lead to incorrect results.
Of course the good thing about python is that there are much less ways to shoot yourself in the foot than with C for example.
But what about other common python mistakes, e.g. 1. incorrect indenting causing code to branch the wrong way, 2. spelling variables wrong so that you are using a new variable initialized to None, 3. duck typing: only finding out at runtime that it doesn’t quack like it should.
There’s a difference between “type(obj) is” and “isinstance.” Isinstance says “True” about sub-classes. If you want to be absolutely sure that something is of a certain type and not a sub-type, you need “is”.
@Carl: Interesting, didn’t knew that
@Matt: while I’m not an expert I have always understood that ‘is’ means ‘the same thing as’ while ‘==’ is ‘the same content as’
@rvl: yes, indeed they work, but it’s always better to try to be more correct and not just ‘ok’
. Btw I don’t get your mistake no. 2, if you use a variable that doesn’t exist it reports a NameError. Incorrect indenting sound to me more like a programmer misattention.
The difference between “==” and “is” is that the “==” operator calls the __eq__() or __cmp__() method on the first object, and “is” doesn’t. It is possible for some instance or other to compare positively to None, even though that behaviour would be surprising and should be avoided.
Example:
class AlwaysEqual:
def __eq__(self, other):
print ‘__eq__() called’
return True
x = AlwaysEqual()
print x == None
print x is None
Since someone who compares a variable to None will usually want to know whether or not it has been instantiated, he should use the “is” operator.
This is made rather more explicit in some other languages such as Java, where you have to call one of the two object’s equals() method explicitly. The world’s log files are full of NullPointerExceptions where someone called equals() on null. This is why a general coding recommendation is to always write
“hello”.equals(greeting)
instead of
greeting.equals(”hello”)
I see often something like this:
a = ['kasdoasudiasud90as9u8d0asdijasodjaiso', 'ksdaosjdiasu9023u8e9i0ajdi23ui0euqw0du9q0','0-230asd0a-s9d0-as9d0-asd0a-sdi0-asid0as-di0as-sdia-']
for x in a:
paint(thisandthat)
instead of for int in a.
@mezo: mmm, didn’t get that one
@Sebastian nice explanation, thank you
@rvl:
Your item 3 on Duck Typing, is it a problem for you? I find Duck Typing works fine for me.
I agree that
if (condition):
is not “pythonic” and does not adhere the PEP 8 style guidelines, but it is not a mistake, since it is valid and does what one would expect it to do. Yes the “(” and “)” are unneeded in this case, but for some they are a welcome sign where the condition begins and where it ends. A style guideline is not a law after all and those who wrote the style guideline introduced their own subjective preferences.
Instead of “if a is not None” and “if a is None”, can’t we just write “if a” and “if not a”? This solution is advocated here: http://jaynes.colorado.edu/PythonIdioms.html
@stephan: It is pythonic if the condition is long and in several parts (like .. && .. || .. ) etc. The pythonic way to do line continuations is using brackets.
When showing code mistakes, never mark the wrong ones in bold but the correct ones. You will make your point better.
@apol: Mmm, good idea. Will remember that next time, thanks.