Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Subclassing RegexObject

5 views
Skip to first unread message
Message has been deleted

Peter Otten

unread,
Dec 16, 2009, 10:42:09 AM12/16/09
to
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

Message has been deleted
0 new messages