DEV Community

Aaron Maxwell
Aaron Maxwell

Posted on

Dark Python Patterns

Here are some terrible ideas you should avoid at all costs:

Import Everything

Avert your eyes from this dangerous code:

from somelib import *
Enter fullscreen mode Exit fullscreen mode

The "import *" will import EVERYTHING contained in that module, and dump it right in your current namespace.

What makes it dangerous is that you won't know there is any problem right away. The problem comes when somelib, or even your own code, gets updated...

Weeks, months, years later...

And suddenly you have a namespace collision that breaks your code, in the most confusing way possible. This create bugs that take ages to even figure out what is going on.

Better: write "import somelib", or "import somelib as sl" (or some other short, handy abbreviation).

That makes all the components in somelib available, safely contained in their own namespace.

Blanket Except Clause

Look away, from the most self-destructive code a Python developer can write:

try:
   do_something()
except:
   pass
Enter fullscreen mode Exit fullscreen mode

What it does is execute the code in the try block.

And if an error is raised - ANY exception whatsoever...

You won't know. You can't know. Until it's too late.

Because the "except: pass" will not only silently suppresses the exception. It will hide from you the fact that there was an error AT ALL.

It does not just hide normal exceptions, like TypeError if you accidently add an integer to a string. Or ValueError, if you convert a string like "not a number" into an int(). If you mis-type a variable name? That's a NameError. And it is COMPLETELY HIDDEN by this diabolical dark pattern. Creating the worst kind of bug, that is almost impossible to detect in development, and will wreak mayhem in production.

Better: pin-point the except clause to the specific exception type you want to ignore. For example, "except ValueError: pass".

Or if that is not appropriate, at least call "logging.exception()" in the except block. Look that up; it gives you a full stack trace in the logs.

Those are two dark Python patterns you should strike from your mind, so you never even think to do them.

Have you found other dark Python patterns? Comment and tell me.

If you liked this, you will enjoy the Powerful Python Newsletter.

Top comments (0)