I have a subclass of the ‘str‘ object and I need to apply it to the application domain. Since the application is full of string literal and str() casts it will take a long time to change all of them to the custom string class. I know it is possible to override ‘str()’ but I’m not sure about string literals.
I know it is not a good idea but the application requires it. Is it possible to do it in Python? And if not, does it require me to modify ‘stringlib‘ which is the C implementation of the ‘str‘ object?
I’m also aware of the fact that modifying the parser to make the application run is considered to be a very bad programming practice. Can this be achieved via an extension rather than a parser modification?
You cannot modify built-in types, e.g. you cannot add new attributes at runtime1:
I would try to parse all literal strings and replace them with the constructor of your custom string subclass. This is first and foremost:
Typically i18n libraries have some kind of string literal detection routines for code, which could come in handy during detection. Once these strings are gathered, it’s more or less just replace.
1 This is also one reason, python isn’t as flexible as ruby. You can’t just write test libraries, that monkey patch core classes and add methods like
should_equalto every object in the runtime. Here is an entertaining tech talk about these nuances and their consequencies: http://blog.extracheese.org/2010/02/python-vs-ruby-a-battle-to-the-death.html