Subclassing RegexObject
Peter Otten
__peter__ at web.de
Wed Dec 16 10:42:09 EST 2009
Tobias Weber wrote:
> how do I subclass or at least add a method to something returned by
> re.compile()?
Let's see:
>>> import re
>>> r = re.compile("yadda")
>>> class S(type(r)): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type '_sre.SRE_Pattern' is not an acceptable base type
So I'm afraid you can't subclass...
>>> def hello(self): print "hello"
...
>>> type(r).hello = hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type
'_sre.SRE_Pattern'
>>> r.hello = hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: '_sre.SRE_Pattern' object has no attribute 'hello'
...nor add a method...
>>> class W(object):
... def __init__(self, match):
... self._match = match
... def __getattr__(self, name):
... return getattr(self._match, name)
... hello = hello
...
>>> def my_compile(*args, **kw):
... m = original_compile(*args, **kw)
... if m is not None:
... return W(m)
...
>>> original_compile = re.compile
>>> re.compile = my_compile
>>> re.compile("yadda").hello()
hello
...but alter the meaning of "something returned by re.compile()" you can.
Now who would want to do that? And why?
Peter
More information about the Python-list
mailing list