Python Newbies Reject A Good Idea

Python using dictionary

The YouTube Short at the bottom of this post illustrates a table-driven alternative to if-else statements in Python. I liked this tip because it was reminiscent of pointers to functions in C, which I wrote about here. The technique allowed me to isolate code to format output to screen, printer, file, or a network socket. 

Back then, it took a bit of work to convince my colleagues the value of this approach, so I was not surprised to see this Python tip dismissed in the comments section:

Please don't do this in production. It's much less clear than an if/else. clarity > conciseness.

Great advice, make it as hard as possible so when your company kicks you [sic] they will have no clue what this does.

Different language, different time, same misunderstanding. The video described the tip in general terms, so I reimplemented it to solve a specific, more relatable, problem:

#!/bin/python3

SCREEN = 1
PRINTER = 2
DISK = 3

def to_screen():
    print ("format for screen")
    
def to_printer():
    print ("format for printer")
    
def to_disk():
    print ("format for disk")
    
def to_default():
    print ("unknown device")
    
devices = {SCREEN: to_screen, PRINTER: to_printer, DISK: to_disk}
write = devices.get(PRINTER, to_default)
write()

I left this snippet in a comment and one response was:

Syntactic sugar!  . . . 

The comment was intended to be dismissive, but it was actually a good sign because it meant the code was readable.  And like the C code I wrote long ago, this technique separated the output devices so that adding code for a new device wouldn't impinge on code in production.

I don't think I swayed many, but I did manage to start a discussion. On the internet, I call that a win.



Comments

Popular posts from this blog

Bookshelf: UNIX A History and a Memoir

Connections

Bookshelf Classic: The C Programming Language