Can I partially override __setattr__?

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__ ?

+4
source share
2 answers

pass filename , content to the superclass for processing

 class MyParser(object): def __setattr__(self, k, v): if k in ['filename', 'content']: super(MyParser, self).__setattr__(k, v) else: # mydict.update(mynewattr) # dict handles other attrs 
+5
source

I think it would be easier to introduce a dictionary-like interface for the contents of the file and leave access to the attribute for internal purposes. However, this is just my opinion.

To answer your question, __setattr__() is called before checking in __dict__ , so you can implement it somehow like this:

 class MyParser(object): specials = ("filename", "content") def __setattr__(self, attr, value): if attr in MyParser.specials: self.__dict__[attr] = value else: # Implement your special behaviour here 
+2
source

All Articles