r/Python • • Apr 25 '21

Tutorial Stop hardcoding and start using config files instead, it takes very little effort with configparser

We all have a tendency to make assumptions and hardcode these assumptions in the code ("it's ok.. I'll get to it later"). What happens later? You move on to the next thing and the hardcode stays there forever. "It's ok, I'll document it.. " - yeah, right!

There's a great package called ConfigParser which you can use which simplifies creating config files (like the windows .ini files) so that it takes as much effort as hardcoding! You can get into the hang of using that instead and it should both help your code more scalable, AND help with making your code a bit more maintainble as well (it'll force you to have better config paramters names)

Here's a post I wrote about how to use configparser:

https://pythonhowtoprogram.com/how-to-use-configparser-for-configuration-files-in-python-3/

If you have other hacks about managing code maintenance, documentation.. please let me know! I'm always trying to learn better ways

1.5k Upvotes

323 comments sorted by

View all comments

77

u/[deleted] Apr 25 '21

I hate ini style configs. Hate. I just use simple variables or dictionaries in a config.py file and import it.

41

u/WillardWhite import this Apr 25 '21

Why not yaml or json?

17

u/RaiseRuntimeError Apr 25 '21

With json you cant have comments.

→ More replies (4)

21

u/[deleted] Apr 25 '21

[removed] — view removed comment

75

u/verdra Apr 25 '21

you don't run any code when you load a json as a dict

importing config.py files can be a security issue.

0

u/[deleted] Apr 25 '21

[deleted]

20

u/dustractor Apr 25 '21

importing the py file means it just runs the code to get the config variables defined so if somebody posted malicious code and suggested to put it in a config, someone else might not know what they were doing and just copy paste it into their config without taking the time to read it and understand what it was doing.

parsing an ini file is safer because it just reads the file, not executes it

32

u/adesme Apr 25 '21

Maybe you've seen people write if __name__ == "__main__": in the scripts/programs. What this does is that what is inside of there only will run if you execute that specific file. If I have a file called config.py, and this file only contains print("hello world!"), then this will be automatically executed when someone writes import .config. That's a security vulnerability if you don't control the file you're importing.

Reading a json file, however, is basically just like an assignment, and doesn't execute anything per se.

0

u/[deleted] Apr 25 '21

[deleted]

14

u/JiggerD Apr 25 '21

There's the concept of security first design.

Establishing that everyone just imports .config files might be fine for you, because you're experienced. But what about that junior Dev that doesn't know better? What about checking and rechecking the file when it's crunch time because the stakeholder meeting is in 2h?

And realistically people stop checking files, because nothing ever happened. People are creatures of habit and with that in mind you'd be better off to establish company guidelines where config files are non-executable.

6

u/POTUS Apr 25 '21

You choose which file to import, but you don’t control what that file does. If the file wants to

os.system(‘rm -rf /usr’)

You can put that in a config.py file, and it will run. If you put it in an ini or json or yaml file, it’s just a bit of text.

→ More replies (2)
→ More replies (1)

7

u/BosseNova Apr 25 '21

But couldnt malicious code be added to any file imported? Does it really introduce a new risk?

6

u/icegreentea Apr 25 '21

Pretty much. In many circumstances (obviously there are always exceptions), if someone can maliciously modify your config file, they can probably maliciously modify your actual program.

The two better arguments for using serialization languages for configuration is:

  • Reduced temptation to put logic into your config. Though definitely not bullet proof (looks at yaml...).

  • Easier for external tools to generate and read your configuration.

9

u/PMental Apr 25 '21

Not if you import json files and the like, even if they contained valid python code it wouldn't execute, just be read as data. Importing a script that sets the data up dynamically however means any other code in the file would execute as well.

4

u/BosseNova Apr 25 '21

You put all code in one file and only import json? I dont think thats common.

→ More replies (2)
→ More replies (3)
→ More replies (2)

16

u/kinygos Pythoneer Apr 25 '21

More structure to the data, more portable formats, and one thing yaml has over json is you can include comments.

9

u/[deleted] Apr 25 '21

In some sense YAML has everything over JSON since JSON is valid YAML. Not a real-world concern though.

7

u/Concretesurfer18 Apr 25 '21

Can a config.py update a setting within it that was changed while the program is running like you can with a json?

4

u/primary157 Apr 25 '21

Not as easy but it is doable.

Btw this is out of the conversation's scope since they are talking about user defined values is a configuration file.

→ More replies (1)
→ More replies (10)
→ More replies (2)

6

u/[deleted] Apr 25 '21 edited Apr 25 '21

I do use yaml in a few cases too. JSON less so. Yaml has the one disadvantage of needing a third party module installed but that's usually not much of an issue.

18

u/[deleted] Apr 25 '21

Yaml has a lot of disadvantages.

  • It is far too clever at trying to guess what you mean in a string, so strings like NO, O13 and 4:30 get unexpectedly translated into a different type

  • By default, many implementations silently allow you to store code as well as data. Python is one of those.

  • A partial Yaml file is still a Yaml file so you have no way to tell if writing is interrupted, or still in process.

  • Indentation errors are easy to make and hard to debug.

More here: https://noyaml.com/

→ More replies (4)

3

u/[deleted] Apr 25 '21

That's my only complaint as well. We need a PEP to bring it into the fold :)

→ More replies (1)
→ More replies (5)

15

u/primary157 Apr 25 '21

Configuration files are mostly better than configuration scripts:

  • no security issues

  • language agnostic

  • if desired it can be updated online at runtime (no need for restart)

  • cloud-native (depend on the adopted format)

  • it can be generated by third party softwares (useful for complex config and services integration config)

However for convenience you can implemented a wrapper called config.py that load the config file and export python structures of your choice.

Note: ini format is platform dependent and isn't standardized. For simple stuff I'd recommend environment variables described in a .env file and read by python-dotenv. For moderately complex config you should use json or yaml. If you're using ini because it supports config sections, then toml is your best choice.

→ More replies (3)

3

u/[deleted] Apr 25 '21

Came here to say something similar. I prefer using a config.py but there are some projects I work on that need to update their own configs from remote config servers (API or MQ). With JSON or ConfigParser these apps can download the updates and change the config on the fly. Can't do that with py files unless I start pickling. And I avoid pickling like it was Hell itself

→ More replies (3)
→ More replies (7)