Member-only story

Write a Lightweight Route Decorator in Python

John Raines
5 min readDec 10, 2022
Photo by Brendan Church on Unsplash

If you’ve used an API framework or two (I love Flask), then you’ve seen this strategy at work. What you might not realize is that it’s saving you the pain and anguish of writing a ton of if..elif..else statements. Under the right conditions, a route decorator is a great way to separate concerns and eliminate control flow in any number of application types — not just APIs.

This post will:

  • Discuss why this pattern is good and when you should use it.
  • Demonstrate a very lightweight, single-module implementation of a route decorator in Python that can be used to make projects more modular and extensible.

And just to add a twinge more clarity, here’s a route decorator that registers a hello_world() handler with our application:

@route("hello-world")
def hello_world():
print("Hello World!")

Let’s go.

Why and when to use a route decorator

Concepts

In many cases, a route decorator handles procedural branching much cleaner than if..else control flows. The main benefit of a route decorator is that it provides stability to central parts of your application, while allowing you or others to extend your application with more peripheral changes…

--

--

John Raines
John Raines

Written by John Raines

For money, I’m a software engineer who primarily works in machine learning platform design. For free, I read fantasy novels and raise children (my own).

No responses yet