Why won't dynaconf read my settings.toml file?

857 Views Asked by At

I"m writing this Q&A to document a painful investigation and resolution in the hopes of saving others the hassle.

I'm using the Python Dynaconf (3.1.11) to manage settings for a package I've written. The settings are stored in a settings.toml file within the package. When I first started using Dynaconf, the recommended usage pattern was

from dynaconf import settings

my_value = settings.MY_KEY
print(my_value)

and the settings.toml file contained

[default]
my_key = 5

and this worked fine. Dynaconf has a documented procedure for where it looks for the settings.toml file. Do be aware of issues around running under a debugger/IDE that may change your working directory - you need to set the current working directory to the top level of your project.

I recently updated my package to follow the newer recommendended practice of initializing the settings using an explicitly created object in my config.py.

# config.py

settings = Dynaconf(
    envvar_prefix="DYNACONF",
    settings_file="settings.toml",
    root_path=Path(__file__).parent,
)

After this seemingly trivial change, attempts to access the settings fails where

my_value = settings.MY_KEY

now throws an error

AttributeError: 'Settings' object has no attribute 'MY_KEY'

which makes it appear as if dynaconf isn't loading/can't find the settings file.

1

There are 1 best solutions below

0
Tom Johnson On

The core issue is that with dyanconf > 3.0

Dynaconf is now envless by default.

see https://github.com/dynaconf/dynaconf/blob/master/3.x-release-notes.md.

and my previous settings.toml file configuration still contains a [default] block. The settings are being loaded correctly, but are "hiding" in settings.DEFAULT.MY_KEY. The proper thing to do is update the settings.toml file to remove the [default] environment specification, making it just

my_key = 5

and all works fine as before. My full investigation is documented at https://github.com/dynaconf/dynaconf/discussions/940.