Member-only story
Getting Rid of Hardcoded Python Variables With the Dotenv Module
Improve code maintainability and security against Google dorking attacks
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: