DEV Community

loading...

Python config file with YAML

tomtucka profile image Tom Withers Updated on ・2 min read

So I was googling for this myself about 4 weeks ago and couldn't find a straight answer, so I'm about to share an easy step by step solution with you.

First off I'm going to assume that you already know some python and have a project setup ready to go inside a venv.

First off lets import yaml,

import yaml

Enter fullscreen mode Exit fullscreen mode

so now lets create a method called load_config

import yaml

def load_config(config_file):

Enter fullscreen mode Exit fullscreen mode

As you can see we are also passing in config_file, Next, we are going to open our config file as a stream using open which is built into python.

import yaml

def load_config(config_file):
    with open(config_file, 'r') as stream:
Enter fullscreen mode Exit fullscreen mode

Using open, we can now open our config file and return a stream. So here we pass in our config_file variable which we defined earlier, we also pass in another parameter which is a string of r this basically tells open which mode we want to open the file in. Now we can move on to loading our YAML file.

def load_config(config_file):
    with open(config_file, 'r') as stream:
        try:
            return yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)
Enter fullscreen mode Exit fullscreen mode

As you can see above, we now load our YAML file using safe_load. It's extremely important to use safe_load here, safe_load only resolves basic YAML tags, whereas load does not. This is also wrapped in a try except block so we can handle any errors.

All that's left to do now is call our method to load the file, make sure you pass in the path to your config.yml file here.

config = load_config('config.yml')
Enter fullscreen mode Exit fullscreen mode

This is my first ever blog post any feedback would be greatly appreciated! :)

Discussion (2)

pic
Editor guide
Collapse
17tranap profile image
Alexandria Tran

Hi thanks for writing this! I really appreciate the detail, but it would have been nice to see an example yaml file since I'm brand new to writing config files. Best!

Some comments have been hidden by the post's author - find out more