I mimic the behavior of the ConfigParser module to write a highly specialized parser that uses a specific structure in the configuration files for the specific application I am working with. Files follow the standard INI structure:
[SectionA] key1=value1 key2=value2 [SectionB] key3=value3 key4=value4
For my application, sections are largely irrelevant; there are no matches between the keys of different sections, and all users only remember the key names; they should never enter any section. As such, I would like to override __getattr__ and __setattr__ in the MyParser class that I create to use shortcuts like this:
config = MyParser('myfile.cfg') config.key2 = 'foo'
The __setattr__ method __setattr__ first try to find a section called key2 and set it to 'foo' if one exists. Assuming that there is no such section, it will look inside each section for a key named key2 . If the key exists, then it gets a new value. If it does not exist, the analyzer will finally raise an AttributeError .
I built a test implementation of this, but the problem is that I also want a couple of straightforward attributes to be freed from this behavior. I want config.filename be a simple string containing the name of the source file, and config.content be a dictionary containing dictionaries for each section.
Is there an easy way to customize the filename and content attributes in the constructor so that they don't lose sight of my custom getters and setters? Will python look for attributes in a __dict__ object before calling a custom __setattr__ ?
source share