Better Programming

Advice for programmers.

Follow publication

Member-only story

5 Ways to get Enums in Python

Martin Thoma
Better Programming
Published in
6 min readJan 24, 2022

--

Photo by Stephen Leonardi on Unsplash

An Enum is a collection of static values, typically strings or integers. They are used pretty often — or at least they should be. At Cashlink, we typically use them to track steps for longer processes.

Enums are a way to group constants. Constants are useful to prevent typos as your editor can warn you when a value is not part of an enum, but it cannot warn you that a string or an integer is invalid. Grouping constants in Enums gives you a couple of advantages.

Before we dive into it, let’s look at some applications for enums.

Examples of Enums

  • Statuses: You’re writing a backend and you want to return a status code, this should be an enum. Instead of writing return 404 you write return status.HTTP_404_NOT_FOUND . In general, variables that contain a finite set of statuses should probably have an Enum as value. Look for “state” or “status”.
  • Choices: It might be salutations a user can choose from or roles of users. Countries of origin, timezones, …. Look for “choice” or sometimes just lists within your code.
  • Types: You could have different types of users, subscriptions, products, …
  • Steps: If you track the user funnel you might have a constant for each step. Depending on that you could have different behavior. The set of all steps could be an Enum.
  • Flags: The Unix permission system which represents Read / Write / Execute as binary flags in a 3-bit sequence is another example of what you would want to do with an Enum.

What you want to do with enums

Get editor support

You can always just use a constant. But when you use an editor, you typically want to get auto-completion by your editor.

Nice representation when printing

There should be a good way to convert it to a string. For example, when you print the HTTP status code I think NOT_FOUND is way better than 404.

Iterate over all values

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Martin Thoma
Martin Thoma

Written by Martin Thoma

I’m a Software Engineer with over 10 years of Python experience (Backend/ML/AI). Support me via https://martinthoma.medium.com/membership

No responses yet

Write a response