Changing the default string object used by the interpreter

Mike McGavin singleify_me_jjeesstteerr at mmccss.vvuuww.aacc.nnzz
Sat Apr 10 02:08:48 EDT 2004


Hi everyone.

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?


For some context, I've been hacking away on an experimental pet project 
for a while.  I have a class that I call zstr, which inherits the 
standard python str class, adding some state information.  The idea is 
that strings can have several representations, such as different ways 
that they're currently escaped, even though all different 
representations are essentially the same string.  If the string contains 
information about its current state, it might be possible to make 
defensive coding in things like web scripting a bit easier.  eg. Any 
code that's unsure of the string's state can re-escape it to make sure, 
whilst the string instance itself can ensure that it doesn't 
accidentally get escaped several times in different parts of the code. 
My somewhat inefficient, buggy and badly documented prototype module is 
available at [ http://www.mcs.vuw.ac.nz/~jester/zstr/ ].

One problem I've discovered anecdotally, however, is that many of the 
strings I'd *like* to naturally treat as zstr objects are ones that are 
initially generated as ordinary strings from external code, such as the 
built-in libraries.  Explicitly wrapping every single string that my 
code receives into a zstr constructor is both ugly and somewhat 
unreliable, since they're so common that I often forget.  Therefore I'd 
like to experiment with ways to bypass this.

What I'd like to try, as mentioned above, is to override Python's string 
creation code, so that it automatically uses a zstr class instead of the 
str class for every string created in the system.  I guess the one 
exception would be where my zstr class inherits and (in some cases) uses 
the regular python str class internally, in which case the real str 
would need to be able to be referenced.

If anyone can suggest a way to do it, I'd love to hear it.


Thanks for any help.
Mike.



More information about the Python-list mailing list