Pattern to match a 1-or-2-arg function call for lib2to3

I have a script that can overwrite a Python module so that all occurrences func(a)are carried over to func2(a is None). Now I want to support as well func(a, msg), becoming func2(a is None, msg), but I cannot find a template that will do this. This shows my attempt:

from lib2to3 import refactor, fixer_base
from textwrap import dedent

PATTERN_ONE_ARG = """power< 'func' trailer< '(' arglist< obj1=any > ')' > >"""

PATTERN_ONE_OR_TWO_ARGS = """power< 'func' trailer< '(' arglist< obj1=any [',' obj2=any] > ')' > >"""


class TestFixer(fixer_base.BaseFix):
    def __init__(self, options, fixer_log):
        # self.PATTERN = PATTERN_ONE_ARG
        self.PATTERN = PATTERN_ONE_OR_TWO_ARGS

        super().__init__(options, fixer_log)

    def transform(self, node, results):
        print("found it")
        return node


class TestRefactoringTool(refactor.MultiprocessRefactoringTool):
    def get_fixers(self):
        fixer = TestFixer(self.options, self.fixer_log)
        return [fixer], []


def test():
    test_script = """
        log.print("hi")
        func(a, "12345")
        func(a, msg="12345")
        func(a)
        """
    refac.refactor_string(dedent(test_script), 'script')


flags = dict(print_function=True)
refac = TestRefactoringTool([], flags)
test()

For each funcone found in the line test_script, I should see one "found", so there are only 3, but I see only 2 printed, implying that it was func(a)not found by the matching pattern. I base the pattern on the latches available in lib2to3.fixes, but I lack subtlety. Does anyone know who to fix PATTERN_ONE_OR_TWO_ARGS so that all 3 functions are found?

, fixer, ( , 24!).

+4
1

:

PATTERN_ONE_OR_TWO_ARGS = """
    power< 'func' trailer< '('
        ( not(arglist | argument<any '=' any>) obj1=any
        | arglist< obj1=any ',' obj2=any > )
    ')' > >
    """

transform():

def transform(self, node, results):
    if 'obj2' in results:
        print("found 2", results['obj1'], results['obj2'])
    else:
        print("found 1", results['obj1'])
    return node

test_script = """
    log.print("hi")
    func(a, "12345")
    func(a, msg="12345")
    func(a)
    func(k=a)
    """

found 2 a  "12345"
found 2 a  msg="12345"
found 1 a

http://python3porting.com/fixers.html#fixers-chapter, , match() . :

PATTERN_ONE_ARG_OR_KWARG   = """power< 'func' trailer< '(' not(arglist) obj1=any                         ')' > >"""
PATTERN_ONE_ARG            = """power< 'func' trailer< '(' not(arglist | argument<any '=' any>) obj1=any ')' > >"""
PATTERN_ONE_KWARG          = """power< 'func' trailer< '(' obj1=argument< any '=' any >                  ')' > >"""
PATTERN_TWO_ARGS_OR_KWARGS = """power< 'func' trailer< '(' arglist< obj1=any ',' obj2=any >              ')' > >"""
+1

Source: https://habr.com/ru/post/1627103/


All Articles