Changing the default string object used by the interpreter

Josiah Carlson jcarlson at uci.edu
Sat Apr 10 18:47:09 EDT 2004


> I'm wondering if anyone can suggest a way, short of directly hacking the 
> python interpreter, to change the default str class to a different one. 
>  ie. So that every time a str instance is created, it uses *my* class 
> instead of the built-in python string.  Is there anything hidden away 
> that can be overloaded that might make this possible to do?

Mike,

I don't believe so.  There would need to be quite a few changes to the C 
internals of Python in order to make /every/ string created or generated 
be of your string class.

I would suggest you just wrap the Python strings with your own class 
whenever you need it...

def myfunct(arg, ...):
     if isinstance(arg, str):
         arg = MyClass(arg)
     #rest of the function body.


With the upcoming decorator syntax for 2.4, you could decorate all of 
your functions to do this, or if you are careful, you could use the 
below now (as long as MyClass was a subclass of object)...

def auto_wrap(*arg_types):
     def funct(function):
         def funct_with_arguments(*args):
             a = []
             for typ, arg in zip(arg_types, args):
                 if isinstance(typ, type):
                     a.append(typ(arg))
                 else:
                     a.append(arg)
              return function(*a)
         return funct_with_arguments
     return funct

#using current syntax..
def myfunct(arg):
     #rest of function body

myfunct = auto_wrap(MyClass)(myfunct)

#using Guido and other's preferred decorator syntax...
[auto_wrap(MyClass)]
def myfunct(arg):
     #rest of function body

#using another group's preferred decorator syntax...
def myfunct(arg) [auto_wrap(MyClass)]:
     #rest of function body


  - Josiah



More information about the Python-list mailing list