Better Programming

Advice for programmers.

Follow publication

Member-only story

Getting Rid of Hardcoded Python Variables With the Dotenv Module

Nicholas Obert
Better Programming
Published in
3 min readAug 24, 2021
Photo by Firmbee.com on Unsplash

Every programmer has written some application hardcoding global settings and variables. While there’s nothing wrong with this using approach in a simple script, it may be worth defining the configuration for a larger application in a more convenient place.

Note: in this article, I’ll use the terms “global variable” and “constant” interchangeably.

Let’s take a look at a few code examples containing constants:

In this case, there’s nothing wrong with writing the URL directly as an argument of the function call. But what if you had to request the same web page multiple times in your application? You would probably go with a global constant like this:

Such an approach is not necessarily bad but can become counterproductive if your code is separated into different files. Defining the same variable in every file is both time-consuming and not maintainable as changing the variable requires you to manually go through every file in your application. In this situation, a settings file might be a good choice.

And to access the constants declared in the settings file named global_settings.py, you just have to import it like this:

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

Responses (4)

Write a response