Spot any errors? let me know, but Unleash your pedant politely please.

Wednesday 9 July 2014

Idiotic Python

One of the problems of learning a programming language is that sometimes things one has written even relatively recently look idiotic.

Sometimes this is due to some bad advice on teh internets. Or perhaps misunderstanding an explanation.

I'd consider that I'm getting reasonably proficient in Python these days. I've had no formal teaching though, and I'm working in isolation, so I don't get feedback from colleagues or a mentor. I'm a lurker at the edge of the Python community.

I'm trying to improve.  I bought Writing Idiomatic Python by Jeff Knupp.  I read through it, skimming for things both do already and don't do/never knew about.  Things I already do were pat-on-the-back affirming, and I think confirmed I'm essentially on the right track.  The rest is a learning opportunity.

When there's a lull at work, which isn't often, I open the book, and pick something to check against in my current project. Yesterday I looked at Avoid comparing directly to True, False, or None and started searching for ==True==False==None; !=True; !=False; !=Nonethinking there'd be a few to fix.  I found far more than I though would be there.  Most disappointingly, quite a few !=False and ==True.

I fixed a lot of this.  Sometimes it seems less readable, so not in all places yet.

A significant penny dropped though, even though I've read this section a few times and nodded to myself as though I understood.  It's the use of is not None to check whether optional parameters have been set.  Sadly, my code is riddled with well meaning but potentially harmful attempts to check optional parameters.

Another penny is teetering on the edge.  In trying to go from harmful to idiomatic, I've made a significant number of minor changes. Some of these alter the order of an if statement to remove negation from the condition:
if not weekend:
    work()
else:
    relax()
if weekend:
    relax()
else:
    work()

None of the changes are difficult, but there's risk of human error here which will be very difficult to find without adequate unit tests.  I don't have unit tests.  I've certainly tested as I've developed, but those tests were transient, not part of a test suite.

In a quick search on Python unit testing, I stumbled across a nice little intro from Jeff Knupp (again).

Sigh. I fear that retro-fitting unit tests is going to expose some unpleasant coupling.


No comments:

Post a Comment