If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Thursday, July 09, 2020

Using module __dir__ and __getattr__ for configuration

PEP 562 added support for module level __dir__ and __getitem__
  • __dir__ is called when the built-in dir function is called on the module
  • __getattr__ is called when an attribute is not found via the regular attribute lookup
Let's use this to build an environment based configuration module. 
  • Conviruation values has a value, environment key and a function to convert from str to right type
    • I'm going to use dataclasses and populate values from environment in __post_init__
    • Complex data types (such as list) should be JSON encoded in the environment variables
  • All configuration values with start with the c_ prefix
  • __dir__ will return a list configuration variables without the c_ prefix
  • __getattr__ will add the c_ prefix and will look for the varialbes in globals
We're adding c_ prefix and removing it to bypass the regular attribute lookup mechanism. If we'll call a variable http_port and user will write config.http_port, our __dir__ function won't be called.

Here's the code

Blog Archive