Is Perl *that* good?

Carl Banks imbosol at aerojockey.invalid
Wed Apr 28 02:01:49 EDT 2004


Paramjit Oberoi wrote:
> 
> 
>>> If only compiled regular expression objects allowed easy access to the
>>> last match object, python regxes would become significantly more
>>> convenient.  For example, today you have to write:
>> 
>> Hmm.  The reason this hasn't been done is that it makes the match
>> method non-reentrant.  For example, suppose you call some functions in
>> between the matching and use of the matched object, like this:
> 
> I agree that that's a good reason...
> 
> So: to make regular expressions convenient, it should be possible to use
> them without necessarily declaring a variable for the regular expression
> object or the match objects.  The former is fairly easy; the latter is
> not.
> 
> The match object needs to have local scope; but, a function cannot access
> the caller's locals without mucking around with sys._getframe(). Is there
> any other way of injecting objects into the caller's namespace?  Are there
> any objects that exist per-frame that could be co-opted for this purpose?
>
> I suppose a convenience module that uses sys._getframe() could be written,

Maybe something like this (I'll leave filling in details and fixing
bugs as an exercise):


    class magic_sre(_sre.whatever):

        _matchstore = {}

        def match(self,s):
            callhash = id(sys._getframe(1))
            match = _sre.whatever.match(self,s)
            self._matchstore[id] = match
            return match

        def matchobj(self):
            callhash = id(sys._getframe(1))
            return self._matchstore[id]


Calling matchobj() gets the match object that was matched in the
calling function using this regexp.  I'm pretty sure using id() of the
frame works: until the calling function exits, no other frame can have
the same id.

It has drawbacks though (only works with CPython, match objects stay
around forever, could accidently hit the storage if another frame has
the same id).


> but I don't think it would be suitable for the standard library.

It's such a silly thing I don't really see the need for it in the
standard library at all.  In fact, I prefer working explicitly with
match objects, working around unweildy testing when I have to.


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list