About Dynamic Class Attributes

Using __getattr__ on a class, you can define attributes dynamically, for example, coming from a configuration dictionary, JSON file, database, or external API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyConfig(object):
    config = settings.MY_CONFIG_DICT

    def __getattr__(self, item):
        return self.config.get(item)

    def get_verbose_name(self):
        return (
            gettext(self.verbose_name) if self.verbose_name 
            else gettext("Configuration")
        )

Then you can get any value from the class or settings dictionary by doing this:

1
2
3
4
my_config = MyConfig()
print(my_config.get_verbose_name())
print(my_config.name)
print(my_config.amount)

Tips and Tricks Programming Python 3