Python ast 模块,arguments() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ast.arguments()

项目:lambdazen    作者:brthor    | 项目源码 | 文件源码
def _transform_function_arguments(left):
    if type(left) is ast.Name:
        names = [left]
    else:
        names = left.elts

    # Python3
    if hasattr(_ast, 'arg'):
        args = [_ast.arg(annotation=None, arg=name.id, col_offset = name.col_offset, lineno=name.lineno) for name in names]
        return ast.arguments(args=args, defaults=[], kwonlyargs=[], kw_defaults=[])

    # Python 2
    arguments = ast.arguments(args=names, defaults=[])
    for argument in arguments.args:
        argument.ctx = ast.Param()

    return arguments
项目:lambdazen    作者:brthor    | 项目源码 | 文件源码
def visit_Compare(self, node):
        """
        :type node: _ast.FunctionDef
        """

        is_lambda_def = len(node.ops) == 1\
                        and type(node.ops[0]) is _ast.Gt \
                        and (type(node.left) is _ast.Tuple or type(node.left) is _ast.Name) \
                        and all(map(lambda t: type(t) == _ast.Name, getattr(node.left, 'elts', [])))

        if not is_lambda_def:
            return node

        arguments = _transform_function_arguments(node.left)
        function_body = node.comparators[0]

        lambda_ast_transform = ast.Lambda(args=arguments,
                                          body=function_body,
                                          lineno=node.lineno,
                                          col_offset=node.col_offset)
        return lambda_ast_transform
项目:appcompatprocessor    作者:mbevilacqua    | 项目源码 | 文件源码
def _check_specific_to_fields(self, name):
        # these tests don't apply for the typename, just the fieldnames
        if name in self.seen_fields:
            raise ValueError('Encountered duplicate field name: '
                             '{0!r}'.format(name))

        if name.startswith('_'):
            raise ValueError('Field names cannot start with an underscore: '
                             '{0!r}'.format(name))


########################################################################
# Returns a function with name 'name', that calls another function 'chain_fn'
# This is used to create the __init__ function with the right argument names and defaults, that
#  calls into _init to do the real work.
# The new function takes args as arguments, with defaults as given.
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_AST_objects(self):
        if not support.check_impl_detail():
            # PyPy also provides a __dict__ to the ast.AST base class.
            return

        x = ast.AST()
        self.assertEqual(x._fields, ())

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(AttributeError):
            x.foobar = 21

        with self.assertRaises(AttributeError):
            ast.AST(lineno=2)

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_AST_objects(self):
        x = ast.AST()
        self.assertEqual(x._fields, ())

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(AttributeError):
            x.foobar = 21

        with self.assertRaises(AttributeError):
            ast.AST(lineno=2)

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_AST_objects(self):
        x = ast.AST()
        self.assertEqual(x._fields, ())

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(AttributeError):
            x.foobar = 21

        with self.assertRaises(AttributeError):
            ast.AST(lineno=2)

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def do_ClassDef(self, node):
        result = []
        name = node.name # Only a plain string is valid.
        bases = [self.visit(z) for z in node.bases] if node.bases else []
        if getattr(node, 'keywords', None): # Python 3
            for keyword in node.keywords:
                bases.append('%s=%s' % (keyword.arg, self.visit(keyword.value)))
        if getattr(node, 'starargs', None): # Python 3
            bases.append('*%s', self.visit(node.starargs))
        if getattr(node, 'kwargs', None): # Python 3
            bases.append('*%s', self.visit(node.kwargs))
        if bases:
            result.append(self.indent('class %s(%s):\n' % (name, ','.join(bases))))
        else:
            result.append(self.indent('class %s:\n' % name))
        for z in node.body:
            self.level += 1
            result.append(self.visit(z))
            self.level -= 1
        return ''.join(result)


    # 2: FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
    # 3: FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list,
    #                expr? returns)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def trace_stubs(self, stub, aList=None, header=None, level=-1):
        '''Return a trace of the given stub and all its descendants.'''
        indent = ' '*4*max(0,level)
        if level == -1:
            aList = ['===== %s...\n' % (header) if header else '']
        for s in stub.out_list:
            aList.append('%s%s' % (indent, s.rstrip()))
        for child in stub.children:
            self.trace_stubs(child, level=level+1, aList=aList)
        if level == -1:
            return '\n'.join(aList) + '\n'

    # 2: ClassDef(identifier name, expr* bases,
    #             stmt* body, expr* decorator_list)
    # 3: ClassDef(identifier name, expr* bases,
    #             keyword* keywords, expr? starargs, expr? kwargs
    #             stmt* body, expr* decorator_list)
    #
    # keyword arguments supplied to call (NULL identifier for **kwargs)
    # keyword = (identifier? arg, expr value)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def visit_FunctionDef(self, node):

        # Create the stub in the old context.
        old_stub = self.parent_stub
        self.parent_stub = Stub('def', node.name, old_stub, self.context_stack)
        self.add_stub(self.stubs_dict, self.parent_stub)
        # Enter the new context.
        self.returns = []
        self.level += 1
        self.context_stack.append(node.name)
        for z in node.body:
            self.visit(z)
        self.context_stack.pop()
        self.level -= 1
        # Format *after* traversing
        # if self.trace_matches or self.trace_reduce:
            # if not self.class_name_stack:
                # print('def %s\n' % node.name)
        self.out('def %s(%s) -> %s' % (
            node.name,
            self.format_arguments(node.args),
            self.format_returns(node)))
        self.parent_stub = old_stub

    # arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_AST_objects(self):
        if not test_support.check_impl_detail():
            # PyPy also provides a __dict__ to the ast.AST base class.
            return

        x = ast.AST()
        self.assertEqual(x._fields, ())

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(AttributeError):
            x.foobar = 21

        with self.assertRaises(AttributeError):
            ast.AST(lineno=2)

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_AST_objects(self):
        x = ast.AST()
        self.assertEqual(x._fields, ())

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(AttributeError):
            x.foobar = 21

        with self.assertRaises(AttributeError):
            ast.AST(lineno=2)

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:Typpete    作者:caterinaurban    | 项目源码 | 文件源码
def add_init_if_not_existing(class_node):
    """Add a default empty __init__ function if it doesn't exist in the class node"""
    for stmt in class_node.body:
        if isinstance(stmt, ast.FunctionDef) and stmt.name == "__init__":
            return
    class_node.body.append(ast.FunctionDef(
        name="__init__",
        args=ast.arguments(
            args=[ast.arg(arg="self", annotation=None, lineno=class_node.lineno)],
            vararg=None,
            kwonlyargs=[],
            kw_defaults=[],
            kwarg=None,
            defaults=[]
        ),
        body=[ast.Pass()],
        decorator_list=[],
        returns=None,
        lineno=class_node.lineno
    ))
项目:insights-core    作者:RedHatInsights    | 项目源码 | 文件源码
def make_plugin_module(rule_body):
    return FavaCode(
        Module(
            body=[
                FunctionDef(
                    name='report',
                    args=arguments(
                        args=[
                            Name(id='shared', ctx=Param()),
                        ],
                        vararg=None,
                        kwarg=None,
                        defaults=[]),
                    body=[
                        Return(
                            value=rule_body.get_ast())],
                    decorator_list=[
                        Call(
                            func=Name(id='fava_rule', ctx=Load()),
                            args=[Name(id=each, ctx=Load()) for each in rule_body.get_parsers()],
                            keywords=[],
                            starargs=None, kwargs=None),
                    ])
            ]),
        [rule_body])
项目:insights-core    作者:RedHatInsights    | 项目源码 | 文件源码
def make_wrapper(new_variables, value):
    """
    Define a set of new variables by createing a call to a lambda function.
    The value becomes the body of the lambda.
    The names of the new_variables become the names of the formal parameters to the lambda.
    The values of the new_variables become the values of the actual arguments to the call.
    """
    return FavaCode(
        Call(
            func=Lambda(
                args=arguments(
                    args=[Name(id=key, ctx=Param()) for key, val in new_variables.iteritems()],
                    vararg=None, kwarg=None, defaults=[]),
                body=value.get_ast()),
            args=[val.get_ast() for key, val in new_variables.iteritems()],
            keywords=[],
            starargs=None,
            kwargs=None),
        [value] + [val for key, val in new_variables.iteritems()])
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def pythoneval(self, args, debug=False):
        refs = [ast.Name("x{0}".format(i), ast.Load()) for i in xrange(len(args))]
        if sys.version_info[0] <= 2:
            params = ast.arguments([ast.Name("x{0}".format(i), ast.Param()) for i in xrange(len(args))], None, None, [])
            fcn = ast.FunctionDef("tmp", params, [ast.Return(self.pythonast(refs))], [])
        else:
            params = ast.arguments([ast.arg("x{0}".format(i), None) for i in xrange(len(args))], None, [], [], None, [])
            fcn = ast.FunctionDef("tmp", params, [ast.Return(self.pythonast(refs))], [], None)

        moduleast = ast.Module([fcn])
        fakeLineNumbers(moduleast)

        if debug:
            print(astToSource(fcn))

        modulecomp = compile(moduleast, "Femtocode", "exec")
        out = {"$importlib": importlib, "$math": math}
        exec(modulecomp, out)

        return out["tmp"](*args)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def build(fcn, args, original=None):
        if all(isinstance(x, Literal) for x in args):
            empty = SymbolTable()
            schema, typedargs, subempty = fcn.buildtyped(args, empty)
            if isinstance(schema, Impossible):
                if schema.reason is not None:
                    reason = "\n\n    " + schema.reason
                else:
                    reason = ""
                complain("Function \"{0}\" does not accept arguments with the given literal types:\n\n    {0}({1}){2}".format(fcn.name, ",\n    {0} ".format(" " * len(fcn.name)).join(pretty(x.schema, prefix="     " + " " * len(fcn.name)).lstrip() for x in typedargs), reason), original)
            else:
                return Literal(fcn.pythoneval([x.value for x in args]), original)

        else:
            if fcn.associative:
                newargs = []
                for arg in args:
                    if isinstance(arg, Call) and arg.fcn == fcn:
                        newargs.extend(arg.args)
                    else:
                        newargs.append(arg)
            else:
                newargs = args

            return Call(fcn, newargs, original)
项目:peval    作者:fjarri    | 项目源码 | 文件源码
def filter_arglist(args, defaults, bound_argnames):
    """
    Filters a list of function argument nodes (``ast.arg``)
    and corresponding defaults to exclude all arguments with the names
    present in ``bound_arguments``.
    Returns a pair of new arguments and defaults.
    """
    new_args = []
    new_defaults = []
    required_args = len(args) - len(defaults)
    for i, arg in enumerate(args):
        if arg.arg not in bound_argnames:
            new_args.append(arg)
            if i >= required_args:
                new_defaults.append(defaults[i - required_args])

    return new_args, new_defaults
项目:peval    作者:fjarri    | 项目源码 | 文件源码
def filter_function_def(function_def, bound_argnames):
    """
    Filters a node containing a function definition (an ``ast.FunctionDef`` object)
    to exclude all arguments with the names present in ``bound_arguments``.
    Returns the new ``ast.arguments`` node.
    """

    assert type(function_def) == ast.FunctionDef

    new_args = filter_arguments(function_def.args, bound_argnames)

    params = dict(
        name=function_def.name,
        args=new_args,
        body=function_def.body,
        decorator_list=function_def.decorator_list,
        returns=function_def.returns)

    return ast.FunctionDef(**params)
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def _setup_args(ctx, args, arg_types, tree):
        # var and kw args are not supported
        if args.vararg:
            raise _errors.TyError("Varargs are not supported.", args.vararg)
        if args.kwarg:
            raise _errors.TyError("Kwargs are not supported.", args.kwarg)
        if len(args.defaults) != 0:
            raise _errors.TyError("Defaults are not supported.", tree)

        variables = ctx.variables
        arguments = args.args
        n_args, n_arg_types = len(arguments), len(arg_types)
        if n_args != n_arg_types:
            raise _errors.TyError(
                "Type specifies {0} arguments but function has {1}.".format(
                    n_arg_types, n_args), 
                tree)
        for arg, arg_type in zip(arguments, arg_types):
            if not isinstance(arg, ast.Name):
                raise _errors.TyError("Argument must be an identifier.", arg)
            arg_id = arg.id
            uniq_id = ctx.generate_fresh_id(arg_id)
            arg.uniq_id = uniq_id
            variables[arg_id] = (uniq_id, arg_type)
            yield arg_id
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def translate_FunctionDef(self, ctx, tree):
        argument_translation = ast.arguments(
            args=[
                ast.Name(id=arg.uniq_id)
                for arg in tree.args.args
            ],
            vararg=None,
            kwarg=None,
            defaults=[])
        body_block = tree.body_block
        body_block_translation = body_block.translate_return(ctx)
        return ast.FunctionDef(
            name=tree.uniq_id,
            args=argument_translation,
            body=body_block_translation,
            decorator_list=[])
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_ListComp(self, t):
        result_append = ast.Attribute(ast.Name('.0', load), 'append', load)
        body = ast.Expr(Call(result_append, [t.elt]))
        for loop in reversed(t.generators):
            for test in reversed(loop.ifs):
                body = ast.If(test, [body], [])
            body = ast.For(loop.target, loop.iter, [body], [])
        fn = [body,
              ast.Return(ast.Name('.0', load))]
        args = ast.arguments([ast.arg('.0', None)], None, [], None, [], [])
        return Call(Function('<listcomp>', args, fn),
                    [ast.List([], load)])
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_ListComp(self, t):
        t = self.generic_visit(t)
        add_element = ast.Attribute(ast.Name('.elements', load), 'append', load)
        body = ast.Expr(Call(add_element, [t.elt]))
        for loop in reversed(t.generators):
            for test in reversed(loop.ifs):
                body = ast.If(test, [body], [])
            body = ast.For(loop.target, loop.iter, [body], [])
        fn = [body,
              ast.Return(ast.Name('.elements', load))]
        args = ast.arguments([ast.arg('.elements', None)], None, [], None, [], [])
        result = Call(Function('<listcomp>', args, fn),
                      [ast.List([], load)])
        return ast.copy_location(result, t)
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_ListComp(self, t):
        t = self.generic_visit(t)
        add_element = ast.Attribute(ast.Name('.elements', load), 'append', load)
        body = ast.Expr(Call(add_element, [t.elt]))
        for loop in reversed(t.generators):
            for test in reversed(loop.ifs):
                body = ast.If(test, [body], [])
            body = ast.For(loop.target, loop.iter, [body], [])
        fn = [body,
              ast.Return(ast.Name('.elements', load))]
        args = ast.arguments([ast.arg('.elements', None)], None, [], None, [], [])
        result = Call(Function('<listcomp>', args, fn),
                      [ast.List([], load)])
        return ast.copy_location(result, t)
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def visit_ListComp(self, t):
        t = self.generic_visit(t)
        add_element = ast.Attribute(ast.Name('.elements', load), 'append', load)
        body = ast.Expr(Call(add_element, [t.elt]))
        for loop in reversed(t.generators):
            for test in reversed(loop.ifs):
                body = ast.If(test, [body], [])
            body = ast.For(loop.target, loop.iter, [body], [])
        fn = [body,
              ast.Return(ast.Name('.elements', load))]
        args = ast.arguments([ast.arg('.elements', None)], None, [], None, [], [])
        result = Call(Function('<listcomp>', args, fn),
                      [ast.List([], load)])
        return ast.copy_location(result, t)
项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def individualizeVariables(a, variablePairs, idNum, imports):
    """Replace variable names with new individualized ones (for inlining methods)"""
    if not isinstance(a, ast.AST):
        return

    if type(a) == ast.Name:
        if a.id not in variablePairs and not (builtInName(a.id) or importedName(a.id, imports)):
            name = "_var_" + a.id + "_" + str(idNum[0])
            variablePairs[a.id] = name
        if a.id in variablePairs:
            a.id = variablePairs[a.id]
    # Override built-in names when they're assigned to.
    elif type(a) == ast.Assign and type(a.targets[0]) == ast.Name:
        if a.targets[0].id not in variablePairs:
            name = "_var_" + a.targets[0].id + "_" + str(idNum[0])
            variablePairs[a.targets[0].id] = name
    elif type(a) == ast.arguments:
        for arg in a.args:
            if type(arg) == ast.arg:
                name = "_arg_" + arg.arg + "_" + str(idNum[0])
                variablePairs[arg.arg] = name
                arg.arg = variablePairs[arg.arg]
        return
    elif type(a) == ast.Call:
        if type(a.func) == ast.Name:
            variablePairs[a.func.id] = a.func.id # save the function name!

    for child in ast.iter_child_nodes(a):
        individualizeVariables(child, variablePairs, idNum, imports)
项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def cleanupEquals(a):
    """Gets rid of silly blah == True statements that students make"""
    if not isinstance(a, ast.AST):
        return a
    if type(a) == ast.Call:
        a.func = cleanupEquals(a.func)
        for i in range(len(a.args)):
            # But test expressions don't carry through to function arguments
            a.args[i] = cleanupEquals(a.args[i])
        return a
    elif type(a) == ast.Compare and type(a.ops[0]) in [ast.Eq, ast.NotEq]:
        l = a.left = cleanupEquals(a.left)
        r = cleanupEquals(a.comparators[0])
        a.comparators = [r]
        if type(l) == ast.NameConstant and l.value in [True, False]:
            (l,r) = (r,l)
        # If we have (boolean expression) == True
        if type(r) == ast.NameConstant and r.value in [True, False] and (eventualType(l) == bool):
            # Matching types
            if (type(a.ops[0]) == ast.Eq and r.value == True) or \
                (type(a.ops[0]) == ast.NotEq and r.value == False):
                transferMetaData(a, l) # make sure to keep the original location
                return l
            else:
                tmp = ast.UnaryOp(ast.Not(addedNotOp=True), l)
                transferMetaData(a, tmp)
                return tmp
        else:
            return a
    else:
        return applyToChildren(a, cleanupEquals)
项目:fz    作者:llllllllll    | 项目源码 | 文件源码
def _compile(self):
        c = _NameSubstitute()
        t = c.visit(copy(self._tree))
        name = repr(self)
        maxarg = max((int(name[1:]) for name in c.name_cache), default=0) + 1
        args = [
            ast.arg(arg='_%d' % n, annotation=None)
            for n in range(1, maxarg)
        ]
        code = compile(
            ast.fix_missing_locations(ast.Module(
                body=[
                    ast.FunctionDef(
                        name=name,
                        args=ast.arguments(
                            args=args,
                            vararg=None,
                            kwonlyargs=[],
                            kw_defaults=[],
                            kwarg=None,
                            defaults=[],
                        ),
                        body=[ast.Return(value=t)],
                        decorator_list=[],
                        returns=None,
                        lineno=1,
                        col_offset=0,
                    ),
                ],
            )),
            name,
            'exec',
        )
        ns = {}
        exec(code, ns)
        return asconstants(**self._constants)(ns[name])
项目:appcompatprocessor    作者:mbevilacqua    | 项目源码 | 文件源码
def _make_fn(name, chain_fn, args, defaults):
    args_with_self = ['_self'] + list(args)
    arguments = [_ast.Name(id=arg, ctx=_ast.Load()) for arg in args_with_self]
    defs = [_ast.Name(id='_def{0}'.format(idx), ctx=_ast.Load()) for idx, _ in enumerate(defaults)]
    if _PY2:
        parameters = _ast.arguments(args=[_ast.Name(id=arg, ctx=_ast.Param()) for arg in args_with_self],
                                    defaults=defs)
    else:
        parameters = _ast.arguments(args=[_ast.arg(arg=arg) for arg in args_with_self],
                                    kwonlyargs=[],
                                    defaults=defs,
                                    kw_defaults=[])
    module_node = _ast.Module(body=[_ast.FunctionDef(name=name,
                                                     args=parameters,
                                                     body=[_ast.Return(value=_ast.Call(func=_ast.Name(id='_chain', ctx=_ast.Load()),
                                                                                       args=arguments,
                                                                                       keywords=[]))],
                                                     decorator_list=[])])
    module_node = _ast.fix_missing_locations(module_node)

    # compile the ast
    code = compile(module_node, '<string>', 'exec')

    # and eval it in the right context
    globals_ = {'_chain': chain_fn}
    locals_ = dict(('_def{0}'.format(idx), value) for idx, value in enumerate(defaults))
    eval(code, globals_, locals_)

    # extract our function from the newly created module
    return locals_[name]


########################################################################
# Produce a docstring for the class.
项目:appcompatprocessor    作者:mbevilacqua    | 项目源码 | 文件源码
def _nt_make(cls, iterable, new=tuple.__new__):
    result = new(cls, iterable)
    if len(result) != len(cls._fields):
        raise TypeError('Expected {0} arguments, got {1}'.format(len(cls._fields), len(result)))
    return result
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'varargannotation',
                                      'kwonlyargs', 'kwarg', 'kwargannotation',
                                      'defaults', 'kw_defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(*range(1, 9))
        self.assertEqual(x.vararg, 2)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'kwarg', 'defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(1, 2, 3, 4)
        self.assertEqual(x.vararg, 2)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'kwarg', 'defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(1, 2, 3, 4)
        self.assertEqual(x.vararg, 2)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_AST_objects(self):
        x = ast.AST()
        self.assertEqual(x._fields, ())
        x.foobar = 42
        self.assertEqual(x.foobar, 42)
        self.assertEqual(x.__dict__["foobar"], 42)

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'varargannotation',
                                      'kwonlyargs', 'kwarg', 'kwargannotation',
                                      'defaults', 'kw_defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(*range(1, 9))
        self.assertEqual(x.vararg, 2)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def _check_arguments(self, fac, check):
        def arguments(args=None, vararg=None, varargannotation=None,
                      kwonlyargs=None, kwarg=None, kwargannotation=None,
                      defaults=None, kw_defaults=None):
            if args is None:
                args = []
            if kwonlyargs is None:
                kwonlyargs = []
            if defaults is None:
                defaults = []
            if kw_defaults is None:
                kw_defaults = []
            args = ast.arguments(args, vararg, varargannotation, kwonlyargs,
                                 kwarg, kwargannotation, defaults, kw_defaults)
            return fac(args)
        args = [ast.arg("x", ast.Name("x", ast.Store()))]
        check(arguments(args=args), "must have Load context")
        check(arguments(varargannotation=ast.Num(3)),
              "varargannotation but no vararg")
        check(arguments(varargannotation=ast.Name("x", ast.Store()), vararg="x"),
                         "must have Load context")
        check(arguments(kwonlyargs=args), "must have Load context")
        check(arguments(kwargannotation=ast.Num(42)),
                       "kwargannotation but no kwarg")
        check(arguments(kwargannotation=ast.Name("x", ast.Store()),
                          kwarg="x"), "must have Load context")
        check(arguments(defaults=[ast.Num(3)]),
                       "more positional defaults than args")
        check(arguments(kw_defaults=[ast.Num(4)]),
                       "length of kwonlyargs is not the same as kw_defaults")
        args = [ast.arg("x", ast.Name("x", ast.Load()))]
        check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
                       "must have Load context")
        args = [ast.arg("a", ast.Name("x", ast.Load())),
                ast.arg("b", ast.Name("y", ast.Load()))]
        check(arguments(kwonlyargs=args,
                          kw_defaults=[None, ast.Name("x", ast.Store())]),
                          "must have Load context")
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_funcdef(self):
        a = ast.arguments([], None, None, [], None, None, [], [])
        f = ast.FunctionDef("x", a, [], [], None)
        self.stmt(f, "empty body on FunctionDef")
        f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
                            None)
        self.stmt(f, "must have Load context")
        f = ast.FunctionDef("x", a, [ast.Pass()], [],
                            ast.Name("x", ast.Store()))
        self.stmt(f, "must have Load context")
        def fac(args):
            return ast.FunctionDef("x", args, [ast.Pass()], [], None)
        self._check_arguments(fac, self.stmt)
项目:tabkit    作者:yandex-tabkit    | 项目源码 | 文件源码
def _make_list_func(tree, field_names_dict, filename=None, add_args=None):
    filename = filename or '<generated>'
    list_name = 'data'

    rewriter = RewriteName(list_name, field_names_dict)

    lambda_args = [ast.Name(id=list_name, ctx=ast.Param(), lineno=0, col_offset=0)]
    for arg in (add_args or []):
        lambda_args.append(
            ast.Name(id=arg, ctx=ast.Param(), lineno=0, col_offset=0)
        )

    tree = rewriter.visit(tree)
    tree = ast.Expression(
        body = ast.Lambda(
            lineno = 0,
            col_offset = 0,
            body = tree.body,
            args = ast.arguments(
                args = lambda_args,
                vararg = None,
                kwarg = None,
                defaults = [],
            )
        ),
    )
    code = compile(tree, filename, 'eval')
    func = eval(code)
    return func
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def visit(self, node):
        '''Return the formatted version of an Ast node, or list of Ast nodes.'''
        if isinstance(node, (list, tuple)):
            return ','.join([self.visit(z) for z in node])
        elif node is None:
            return 'None'
        else:
            assert isinstance(node, ast.AST), node.__class__.__name__
            method_name = 'do_' + node.__class__.__name__
            method = getattr(self, method_name)
            s = method(node)
            # assert type(s) == type('abc'), (node, type(s))
            assert g.isString(s), type(s)
            return s

    # Contexts...


    # 2: ClassDef(identifier name, expr* bases,
    #             stmt* body, expr* decorator_list)
    # 3: ClassDef(identifier name, expr* bases,
    #             keyword* keywords, expr? starargs, expr? kwargs
    #             stmt* body, expr* decorator_list)
    #
    # keyword arguments supplied to call (NULL identifier for **kwargs)
    # keyword = (identifier? arg, expr value)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def do_Store(self, node):
        return 'Store'

    # Operands...


    # 2: arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)
    # 3: arguments = (arg*  args, arg? vararg,
    #                arg* kwonlyargs, expr* kw_defaults,
    #                arg? kwarg, expr* defaults)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def do_arguments(self, node):
        '''Format the arguments node.'''
        kind = self.kind(node)
        assert kind == 'arguments', kind
        args = [self.visit(z) for z in node.args]
        defaults = [self.visit(z) for z in node.defaults]
        # Assign default values to the last args.
        args2 = []
        n_plain = len(args) - len(defaults)
        for i in range(len(args)):
            if i < n_plain:
                args2.append(args[i])
            else:
                args2.append('%s=%s' % (args[i], defaults[i - n_plain]))
        if isPython3:
            args  = [self.visit(z) for z in node.kwonlyargs]
            defaults = [self.visit(z) for z in node.kw_defaults]
            n_plain = len(args) - len(defaults)
            for i in range(len(args)):
                if i < n_plain:
                    args2.append(args[i])
                else:
                    args2.append('%s=%s' % (args[i], defaults[i - n_plain]))
            # Add the vararg and kwarg expressions.
            vararg = getattr(node, 'vararg', None)
            if vararg: args2.append('*' + self.visit(vararg))
            kwarg = getattr(node, 'kwarg', None)
            if kwarg: args2.append('**' + self.visit(kwarg))
        else:
            # Add the vararg and kwarg names.
            name = getattr(node, 'vararg', None)
            if name: args2.append('*' + name)
            name = getattr(node, 'kwarg', None)
            if name: args2.append('**' + name)
        return ','.join(args2)

    # 3: arg = (identifier arg, expr? annotation)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def __init__ (self):
        '''Ctor for StandAloneMakeStubFile class.'''
        self.options = {}
        # Ivars set on the command line...
        self.config_fn = None
            # self.finalize('~/stubs/make_stub_files.cfg')
        self.enable_unit_tests = False
        self.files = [] # May also be set in the config file.
        # Ivars set in the config file...
        self.output_fn = None
        self.output_directory = self.finalize('.')
            # self.finalize('~/stubs')
        self.overwrite = False
        self.prefix_lines = []
        self.trace_matches = False
        self.trace_patterns = False
        self.trace_reduce = False
        self.trace_visitors = False
        self.update_flag = False
        self.verbose = False # Trace config arguments.
        self.warn = False
        # Pattern lists, set by config sections...
        self.section_names = (
            'Global', 'Def Name Patterns', 'General Patterns')
        self.def_patterns = [] # [Def Name Patterns]
        self.general_patterns = [] # [General Patterns]
        self.names_dict = {}
        self.op_name_dict = self.make_op_name_dict()
        self.patterns_dict = {}
        self.regex_patterns = []
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def do_Compare(self, node):
        '''
        StubFormatter ast.Compare visitor for these ops:
        '==', '!=', '<', '<=', '>', '>=', 'is', 'is not', 'in', 'not in',
        '''
        s = 'bool' # Correct regardless of arguments.
        ops = ','.join([self.op_name(z) for z in node.ops])
        self.trace_visitor(node, ops, s)
        return s

    # If(expr test, stmt* body, stmt* orelse)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def visit_ClassDef(self, node):

        # Create the stub in the old context.
        old_stub = self.parent_stub
        self.parent_stub = Stub('class', node.name,old_stub, self.context_stack)
        self.add_stub(self.stubs_dict, self.parent_stub)
        # Enter the new context.
        self.class_name_stack.append(node.name)
        self.context_stack.append(node.name)
        if self.trace_matches or self.trace_reduce:
            print('\nclass %s\n' % node.name)
        # Format...
        bases = [self.visit(z) for z in node.bases] if node.bases else []
        if getattr(node, 'keywords', None): # Python 3
            for keyword in node.keywords:
                bases.append('%s=%s' % (keyword.arg, self.visit(keyword.value)))
        if getattr(node, 'starargs', None): # Python 3
            bases.append('*%s', self.visit(node.starargs))
        if getattr(node, 'kwargs', None): # Python 3
            bases.append('*%s', self.visit(node.kwargs))
        if not node.name.startswith('_'):
            if node.bases:
                s = '(%s)' % ', '.join([self.format(z) for z in node.bases])
            else:
                s = ''
            self.out('class %s%s:' % (node.name, s))
        # Visit...
        self.level += 1
        for z in node.body:
            self.visit(z)
        self.context_stack.pop()
        self.class_name_stack.pop()
        self.level -= 1
        self.parent_stub = old_stub

    # 2: FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
    # 3: FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list,
    #                expr? returns)
项目:dotfiles    作者:zchee    | 项目源码 | 文件源码
def format_arguments(self, node):
        '''
        Format the arguments node.
        Similar to AstFormat.do_arguments, but it is not a visitor!
        '''
        assert isinstance(node,ast.arguments), node
        args = [self.raw_format(z) for z in node.args]
        defaults = [self.raw_format(z) for z in node.defaults]
        # Assign default values to the last args.
        result = []
        n_plain = len(args) - len(defaults)
        # pylint: disable=consider-using-enumerate
        for i in range(len(args)):
            s = self.munge_arg(args[i])
            if i < n_plain:
                result.append(s)
            else:
                result.append('%s=%s' % (s, defaults[i - n_plain]))
        # Now add the vararg and kwarg args.
        name = getattr(node, 'vararg', None)
        if name:
            if hasattr(ast, 'arg'): # python 3:
                name = self.raw_format(name)
            result.append('*' + name)
        name = getattr(node, 'kwarg', None)
        if name:
            if hasattr(ast, 'arg'): # python 3:
                name = self.raw_format(name)
            result.append('**' + name)
        return ', '.join(result)
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def make_args_list(args):
    return ast.arguments(args=args, vararg=None, kwarg=None, defaults=[])
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'kwarg', 'defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(1, 2, 3, 4)
        self.assertEqual(x.vararg, 2)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_AST_objects(self):
        x = ast.AST()
        self.assertEqual(x._fields, ())
        x.foobar = 42
        self.assertEqual(x.foobar, 42)
        self.assertEqual(x.__dict__["foobar"], 42)

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_arguments(self):
        x = ast.arguments()
        self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
                                      'kw_defaults', 'kwarg', 'defaults'))

        with self.assertRaises(AttributeError):
            x.vararg

        x = ast.arguments(*range(1, 7))
        self.assertEqual(x.vararg, 2)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _check_arguments(self, fac, check):
        def arguments(args=None, vararg=None,
                      kwonlyargs=None, kwarg=None,
                      defaults=None, kw_defaults=None):
            if args is None:
                args = []
            if kwonlyargs is None:
                kwonlyargs = []
            if defaults is None:
                defaults = []
            if kw_defaults is None:
                kw_defaults = []
            args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
                                 kwarg, defaults)
            return fac(args)
        args = [ast.arg("x", ast.Name("x", ast.Store()))]
        check(arguments(args=args), "must have Load context")
        check(arguments(kwonlyargs=args), "must have Load context")
        check(arguments(defaults=[ast.Num(3)]),
                       "more positional defaults than args")
        check(arguments(kw_defaults=[ast.Num(4)]),
                       "length of kwonlyargs is not the same as kw_defaults")
        args = [ast.arg("x", ast.Name("x", ast.Load()))]
        check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
                       "must have Load context")
        args = [ast.arg("a", ast.Name("x", ast.Load())),
                ast.arg("b", ast.Name("y", ast.Load()))]
        check(arguments(kwonlyargs=args,
                          kw_defaults=[None, ast.Name("x", ast.Store())]),
                          "must have Load context")
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_funcdef(self):
        a = ast.arguments([], None, [], [], None, [])
        f = ast.FunctionDef("x", a, [], [], None)
        self.stmt(f, "empty body on FunctionDef")
        f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
                            None)
        self.stmt(f, "must have Load context")
        f = ast.FunctionDef("x", a, [ast.Pass()], [],
                            ast.Name("x", ast.Store()))
        self.stmt(f, "must have Load context")
        def fac(args):
            return ast.FunctionDef("x", args, [ast.Pass()], [], None)
        self._check_arguments(fac, self.stmt)