Painful code
Student Login

Painful code

When I look at my code, and see two functions that are almost the same, it hurts.

It's painful. It's visceral. As soon as possible, I want to replace those two functions with a single generic version. And it'll bug me until I do.

It's the principle of DRY. Don't Repeat Yourself. And a good language will give you plenty of tools to do that, so you can DRY better.

What kinds of tools? Well, object-oriented programming is one. Many languages have good object systems, so you can leverage OOP. Python has a GREAT object system. And some languages have good function abstractions as well. That can be a MAGNIFICENT tool. Not many languages have this, really, but Python does.

Actually, Python has another tool that is very uncommon: you can write decorators.

Do you know about decorators? It's basically a way to add behavior around a large of group of functions or methods.

By "add behavior", I mean "lines of code". And by "around", I mean adding them before the function starts; after it returns; or both.

Sounds interesting, yes? Like I said, few languages have something like this. And it's powerful. By writing good decorators, you can capture patterns of code reuse that are *impossible* to capture any other way.

You can DRY in new ways, in other words.

It's a shame so few Python developers ever learn to write decorators. That's because it's frankly hard to learn. You first need to master several advanced features of Python. And then figure out how to combine them together in weird ways. By my estimate, fewer than 1% of Python developers ever learn to write decorators. Which gives you a MASSIVE FREAKING ADVANTAGE when you do.

Because it's so useful, the Powerful Python book includes in-depth chapters leading you into that 1%. Like one reader said: "Your chapter on decorators is the best I've seen on the topic."

Newsletter Bootcamp

Book Courses