Thursday, July 9, 2020

pythonwise: 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



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...