Creating True Global Functions by Modifying Builtins

Kamilche klachemin at home.com
Wed Jun 9 19:51:08 CEST 2004


I really, really want a handful of 'true' global functions, ones that
can be called from anywhere without requiring importing. So I added it
to the 'builtins' of Python, and it appeared to work. :-O  Will this
have unintended side-effects? :-D  Take a look:

def traceme(s):
    print "trace:", s

import types

def BuiltInFunctions():
    callables = (types.BuiltinFunctionType, \
                 types.BuiltinMethodType, \
                 types.CodeType, types.FunctionType, \
                 types.GeneratorType, \
                 types.MethodType, \
                 types.UnboundMethodType)
    builtins = globals()['__builtins__']
    d = vars(builtins)
    list = []
    for name, value in d.items():
        if type(value) in callables:
            list.append(name)
    list.sort()
    return list

def AddBuiltIn(name, fn):
    builtins = globals()['__builtins__']
    d = vars(builtins)
    if d.has_key(name):
        raise Exception("Can't override built in " + \
                        " function " + name + "!")
    d[name] = fn


print "Built in functions before adding 'trace':"
print BuiltInFunctions()
AddBuiltIn('trace', traceme)
print "Built in functions after adding 'trace':"
print BuiltInFunctions()

trace("hi there")



More information about the Python-list mailing list