Hi all,
I wanted to share with you something I’ve been researching, and ask if any of you have advice on how I should proceed with it (or even if I should).
I want to wrap a string in a class, which may freely modify the string, but which will seamlessly evaluate as that string.
Print, format, concatenation with “a” + obj, everything. As far as the interpreter is concerned, an instance of this StringLike object should be a string, but one which happens to have any user-defined functionality as well.
I’ve been working on this for quite a while now - originally I did try subclassing the str metaclass, and inheriting directly from string. That worked very well, apart from one small problem: the object was still actually a string, and therefore totally immutable. I could override all the magic methods to return modified strings, but print( myStringLike ) or otherwise directly evaluating the object would always return the original string from its initialisation.
I’ve since started again with this: https://gist.github.com/edart76/f805fb9200a3a529c5178f2413557712
It’s a different, cleaner approach, which allows more control through methods, total freedom to modify the string, a clear interface for doing so, and more conventional class/metaclass structure - however, as noted in the gist, the new object is not a string, which causes problems with concatenation and probably many more things I haven’t found yet.
Long story short, I need to make this random object very very closely resemble a string, ideally close enough that isinstance(StringLike, str) evaluates to true. I don’t know if I should pursue multiple inheritance in the metaclass, how any of this interacts with the special interpreter rules regarding strings themselves, or even if this is possible without ctypes. I don’t know anything really.
If anyone here can share a perspective on this, I would be very grateful to hear it, I’m literally going bald over it.
Thank you