Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Your most unpythonic code snippet [closed]

Tags:

python

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.

like image 417
schickb Avatar asked Jan 17 '09 20:01

schickb


Video Answer


2 Answers

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')
like image 188
EvilRyry Avatar answered Oct 12 '22 06:10

EvilRyry


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
like image 39
Federico A. Ramponi Avatar answered Oct 12 '22 07:10

Federico A. Ramponi