I am an experienced developer new to python, and still catching myself writing correct but unpythonic code. I thought it might be enlightening and entertaining to see small examples of python code people have written that in some way clashes with the generally preffered way of doing things.
I'm interested in code you actually wrote rather than invented examples. Here is one of mine: In code that was expecting a sequence that could be empty or None I had
if data is not None and len(data) > 0:
I later reduced that to
if data:
The simpler version allows additional true values like True or 10, but that's ok because the caller made a mistake and will get an exception from the statements within the if.
I find manual type checking the most "unpythonic" (although bad in general too). There's two usual cases this is abused. The first is when the logic of the function differs based on the type of the argument. For instance:
def doStuff (myVar):
if isinstance (myVar, str):
# do stuff
pass
elif isinstance (myVar, int):
# do other stuff
pass
The second is when the programmer tries to make a strongly typed function like you would expect to find in a statically typed language.
def doStuff (myVar):
if not isinstance (myVar, int):
raise TypeError ('myVar must be of type int')
Some unpythonic habits that one could inherit from C-like languages:
1) The unnecessary semicolon:
printf "Hello world";
2) Unnecessary indexes:
# Bad
for i in range(len(myList)):
print myList[i]
# Good
for item in myList:
print item
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With