[Python-porting] 2to3 pattern matching help needed.

Lennart Regebro regebro at gmail.com
Wed Apr 8 08:50:58 CEST 2009


On Wed, Apr 8, 2009 at 01:24, Benjamin Peterson <benjamin at python.org> wrote:
> 2009/4/7 Lennart Regebro <regebro at gmail.com>:
>> Help! I need a pattern to match the following code:
>>
>> @implementor(IFoo)
>> class C(object):
>>    implements(IFoo)
>>    classProvides(IFooFactory
>>
>> find_pattern claims that this code should match:
>>
>> "decorated< decorator< '@' 'implementer' '(' 'IFoo' ')' '\n' >
>> classdef< 'class' 'C' '(' 'object' ')' ':' suite< '\n' '    '
>> simple_stmt< power< 'implements' trailer< '(' 'IFoo' ')' > > '\n' >
>> simple_stmt< power< 'classProvides' trailer< '(' 'IFooFactory' ')' > >
>> '\n' > '' > > >"
>>
>> It does not match.
>
> 2to3 has a hard time working with more than a single statements and
> lines of code especially classes. You can't use the pattern matcher
> for everything, unfortunately. This pattern matches a class with the
> decorator you want:
>
> decorated< decorator< '@' 'implementor' '(' 'IFoo' ')' any >
> class=classdef< any* > >
>
> Once you that matches, I suggest you traverse the classdef node
> programmatically to find simple_stmts containing the lines you're
> interested in. This is similar to what lib2to3/fixes/fix_metaclass.py
> does.

Well, that didn't help, but it made me realize I was barking up the
wrong three. The problem was that I created a new node tree that
wasn't what it would have looked like like if it had been parsed from
source (although it would generate valid code when made into a str). I
fixed that, and did some other changes, and I got past this obstacle
too.

Tricky stuff this.

-- 
Lennart Regebro: Pythonista, Barista, Notsotrista.
http://regebro.wordpress.com/
+33 661 58 14 64


More information about the Python-porting mailing list