Wishlist: string attributes

Alex Martelli aleax at aleax.it
Thu Mar 27 13:33:51 EST 2003


Nicodemus wrote:
   ...
> Why not make this an attribute of the str type? You could access them
> using "str.digits".

Yes, that's exactly what I'd like to see.  It _might_ be neat if, as
somebody else suggested, str.digits was of a special type inheriting
from str but overring __contains__, e.g.:

class specialstr(str):
    def __new__(cls, initval, checker):
        return str.__new__(cls.initval)
    def __init__(self, initval, checker):
        self.checker = checker
    def __contains__(self, c)
        return self.checker(c)

# can't set attributes of str, but, if we could...:
str.digits = specialstr(string.digits, str.isdigit)
str.letters = specialstr(string.letters, str.isalpha)
# etc, etc

just to speed up idioms such as "if c in str.digits:", rather than
asking for them to be recoded as "if c.isdigit():" directly.  But
I'm not sure the added value would be sufficient to justify such
a provision of "more than one obvious way to do it", anyway!-)


Alex





More information about the Python-list mailing list