Overriding builtin getattr method

Diez B. Roggisch deets at nospam.web.de
Tue Oct 3 11:05:07 CEST 2006


>>     I have data stored in the database which has special characters
>> like <, > etc.
>> Case 1: Whenever I wanted to present the output to a browser
>>       I need to escape these special characters into the browser
>> equivalent like &lt;  &gt; etc.( for example by using the cgi module)
>> Case 2: Whenever I wanted to present the output to some client other
>> than a browser, I wanted to present the data as it is stored in the
>> database.
>>
>> For doing this I thought of overriding the __builtin__.__getattr__
>> method.
>> I am wondering if there is any other way of achieving this. I have
>> loads of files that get the attribute values of objects stored in the
>> database and I do not want to manually change the way of DB access in
>> those files. I rather prefer a centralized way to achieve this.

The centralized approach to this is certainly not achieved by 
overloading getattr alone - because even if it was possible to do so 
(which it isn't), the implementation needed a way to know when to use 
escaping or not. Which would be signaled by some means, e.g. a 
thread-local variable or even a global (shudder).

This signal gets set in the code that decides that it wants the data 
escaped - or not. And thus the code looks like this:

needs_escaping()
work_with_objects()
no_escaping_anymore()

But that is fragile, think of work_with_objects() throwing an exception 
and the no_escaping_anymore() isn't called again.

So the better approach is to gather the data as it is, and when you 
transform it to something that requires escaping, do it there.

That means: the way to do it is to use one of the gazillion web 
templating systems that already do this escaping for you.

Diez



More information about the Python-list mailing list