Type subclassing: bug or feature

Chris Liechti cliechti at gmx.net
Thu Jun 13 17:24:09 EDT 2002


aahz at pythoncraft.com (Aahz) wrote in news:aeau48$111$1 at panix1.panix.com:

> Consider the following code:
> 
> class MyStr(str):
>     def contains(self, value):
>         return self.find(value) >= 0
> 
> s = MyStr("hello, world!")
> s = s.capitalize()
> if s.contains('Hello'):
>     print "Found it!"
> 
> It fails with an AttributeError when it calls s.contains(), because
> s.capitalize() returned a str instead of a MyStr.  Anyone want to take a
> whack at defending this as the correct behavior?

solving this at the C level would require patching many stingobject factory 
functions... e.g. PyString_FromStringAndSize for capitalize(). but it would 
indeed be desireable.

i think it would like to have a even more genral mechanism. i would like to 
have a possibility to replace the builtin type. e.g. i could replace the 
builtin "str" and all strings from now on would be instaces of my class. 
but that's clearly impossible in the current implementation.

<hacker warning>
like Bengt already sugested just automated ;-) ...

>>> class mstr(str):
... 	for name,m in str.__dict__.items():
... 		if type(m) == type(str.find):
... 			exec """def %s(*args, **kwargs):
... 					q = str.%s(*args, **kwargs)
... 					if type(q) is str: return mstr(q)
... 					else: return q\n""" % (name, name)
... 	def __contains__(self, other):
... 		return str.find(self, other) >= 0
... 	
>>> s = mstr("hello")
>>> type(s.capitalize())
<class '__main__.mstr'>
>>> 'll' in s.capitalize()
1
</hacker warning>

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list