... now that we have fancy new type unification:
from _py_htmltext import _format_re, _wraparg, _DictWrapper, _escape_string
from types import TupleType
class htmltext(str):
def __repr__(self):
return '' % str.__repr__(self)
# or use super(), but there's no benefit since 'str' is not complicated
return '' % super(str, self).__repr__()
def __mod__(self, args):
codes = []
usedict = 0
for format in _format_re.findall(self):
if format[-1] != '%':
if format[1] == '(':
usedict = 1
codes.append(format[-1])
if usedict:
args = _DictWrapper(args)
else:
if len(codes) == 1 and not isinstance(args, TupleType):
args = (args,)
args = tuple([_wraparg(arg) for arg in args])
return self.__class__(str.__mod__(self, args))
def __add__(self, other):
if isinstance(other, str):
return self.__class__(str.__add__(self, _escape_str(other)))
else:
return NotImplemented
def __radd__(self, other):
if isinstance(other, str):
return self.__class__(str.__add__(_escape_str(other), self))
else:
return NotImplemented
def join(self, items):
quoted_items = []
for item in items:
if isinstance(item, str):
quoted_items.append(_escape_str(item))
else:
raise TypeError(
'join() requires string arguments (got %r)' % item)
return self.__class__(str.join(self, quoted_items))
def startswith(self, s):
return str.startswith(self, _escape_str(s))
# ...
def _escape_str(s):
if isinstance(s, htmltext):
return str(s)
else:
return _escape_string(s)
I'm sure the new "subtype" C API would allow the same to be written in C.
This htmltext *can* be used where a string is expected.
But I'm sure you guys already thought of it and rejected it. How come?