abusing __builtins__

Christian Tanzer tanzer at swing.co.at
Mon Feb 26 02:58:42 EST 2001


Thomas Wouters <thomas at xs4all.net> wrote:

> > Consider the following imaginary example. In a project where there is no
> > need to open files one replaces the open function. So this project will
> > never manage to open a file but aside from that it will continue to work
> > as designed.
> 
> This is a different situation entirely! As long as you provide the same
> interface for the function you are replacing, and *intend* for it to replace
> the normal 'open' call, there is no problem. You might run into a problem in
> the future, though, when builtins becomes unwritable. (Which, for all we
> know, might happen in Python 2.3 -- but not without warnings first <wink> :)

I sure hope that won't happen.

Sometimes there are pretty good reasons to augment builtins.

For instance, I recently implemented a Class_Proxy. To make
Class_Proxy instances fully compatible with the classes they proxy, I
used:

###############################################################################
def _fix_builtins () :
    import __builtin__

    def isinstance (object, C, isinstance = __builtin__.isinstance) :
        if hasattr (C, "_Class") :
            C = C._Class
        return isinstance (object, C)
    isinstance.__doc__     = __builtin__.isinstance.__doc__
    __builtin__.isinstance = isinstance

    def issubclass (C, B, issubclass = __builtin__.issubclass) :
        if hasattr (C, "_Class") : C = C._Class
        if hasattr (B, "_Class") : B = B._Class
        return issubclass (C, B)
    issubclass.__doc__     = __builtin__.issubclass.__doc__
    __builtin__.issubclass = issubclass
    
_fix_builtins ()
del _fix_builtins
###############################################################################

Works like a charm. I could retrofit the class proxies into 
existing applications without any changes in the users of the classes
to be proxied.

If builtins were readonly, every place where a class proxy is used
would need to import Class_Proxy explicitly. This defeats the purpose
of the proxies. 

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list