Python ast.AsyncFunctionDef() Examples

The following are 30 code examples of ast.AsyncFunctionDef(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: outline_quickly.py    From blackmamba with MIT License 6 votes vote down vote up
def _generate_nodes(parent, level=0, breadcrumb=''):
        nodes = []

        for child in parent.body:
            if isinstance(child, ast.ClassDef):
                style = OutlineNodeItem.Style.cls
            elif isinstance(child, ast.FunctionDef) or isinstance(child, ast.AsyncFunctionDef):
                style = OutlineNodeItem.Style.fn
            else:
                style = None

            if style:
                node = OutlineNodeItem(style, child.name, child.lineno, child.col_offset, level, breadcrumb)
                nodes.append(node)
                if breadcrumb:
                    bc = '{} • {}'.format(breadcrumb, child.name)
                else:
                    bc = child.name
                child_nodes = OutlineDataSource._generate_nodes(child, level + 1, bc)
                if child_nodes:
                    nodes.extend(child_nodes)

        return nodes 
Example #2
Source File: bugbear.py    From flake8-bugbear with MIT License 6 votes vote down vote up
def check_for_b012(self, node):
        def _loop(node, bad_node_types):
            if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
                return

            if isinstance(node, (ast.While, ast.For)):
                bad_node_types = (ast.Return,)

            elif isinstance(node, bad_node_types):
                self.errors.append(B012(node.lineno, node.col_offset))

            for child in ast.iter_child_nodes(node):
                _loop(child, bad_node_types)

        for child in node.finalbody:
            _loop(child, (ast.Return, ast.Continue, ast.Break)) 
Example #3
Source File: model.py    From staticfg with Apache License 2.0 6 votes vote down vote up
def get_source(self):
        """
        Get a string containing the Python source code corresponding to the
        statements in the block.

        Returns:
            A string containing the source code of the statements.
        """
        src = ""
        for statement in self.statements:
            if type(statement) in [ast.If, ast.For, ast.While]:
                src += (astor.to_source(statement)).split('\n')[0] + "\n"
            elif type(statement) == ast.FunctionDef or\
                 type(statement) == ast.AsyncFunctionDef:
                src += (astor.to_source(statement)).split('\n')[0] + "...\n"
            else:
                src += astor.to_source(statement)
        return src 
Example #4
Source File: function_description.py    From darglint with MIT License 6 votes vote down vote up
def _has_return(fun):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool
    """Return true if the function has a fruitful return.

    Args:
        fun: A function node to check.

    Returns:
        True if there is a fruitful return, otherwise False.

    """
    def skip(f):
        return f != fun and isinstance(f, FunctionDef)

    for node in _walk(fun, skip):
        if isinstance(node, ast.Return) and node.value is not None:
            return True
    return False 
Example #5
Source File: function_description.py    From darglint with MIT License 6 votes vote down vote up
def _get_decorator_names(fun):  # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> List[str]  # noqa: E501
    """Get decorator names from the function.

    Args:
        fun: The function whose decorators we are getting.

    Returns:
        The names of the decorators. Does not include setters and
        getters.

    """
    ret = list()
    for decorator in fun.decorator_list:
        # Attributes (setters and getters) won't have an id.
        if hasattr(decorator, 'id'):
            ret.append(getattr(decorator, 'id'))
    return ret 
Example #6
Source File: function_description.py    From darglint with MIT License 6 votes vote down vote up
def get_line_number_from_function(fn):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> int
    """Get the line number for the end of the function signature.

    The function signature can be farther down when the parameter
    list is split across multiple lines.

    Args:
        fn: The function from which we are getting the line number.

    Returns:
        The line number for the start of the docstring for this
        function.

    """
    line_number = fn.lineno
    if hasattr(fn, 'args') and fn.args.args:
        last_arg = fn.args.args[-1]
        line_number = last_arg.lineno
    return line_number 
Example #7
Source File: compiler.py    From Transcrypt with Apache License 2.0 6 votes vote down vote up
def getAdjacentClassScopes (self, inMethod = False):
        # Work backward until finding an interruption in the chain
        # Needed to fix destructuring assignment in nested classes and to make super () work
        # The latter needs inMethod, since supported use of super () is directly or indirectly enclosed in a method body
        reversedClassScopes = []
        for scope in reversed (self.scopes):
            if inMethod:
                if type (scope.node) in (ast.FunctionDef, ast.AsyncFunctionDef):
                    continue
                else:
                    inMethod = False

            if type (scope.node) != ast.ClassDef:
                break
            reversedClassScopes.append (scope)
        return reversed (reversedClassScopes) 
Example #8
Source File: compiler.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def visit_Nonlocal (self, node):
        self.getScope (ast.FunctionDef, ast.AsyncFunctionDef) .nonlocals.update (node.names) 
Example #9
Source File: bugbear.py    From flake8-bugbear with MIT License 5 votes vote down vote up
def walk_function_body(self, node):
        def _loop(parent, node):
            if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
                return
            yield parent, node
            for child in ast.iter_child_nodes(node):
                yield from _loop(node, child)

        for child in node.body:
            yield from _loop(node, child) 
Example #10
Source File: ast3.py    From gast with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_AsyncFunctionDef(self, node):
            new_node = gast.AsyncFunctionDef(
                self._visit(node.name),
                self._visit(node.args),
                self._visit(node.body),
                self._visit(node.decorator_list),
                self._visit(node.returns),
                None,  # type_comment
            )
            gast.copy_location(new_node, node)
            return new_node 
Example #11
Source File: ast3.py    From gast with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_AsyncFunctionDef(self, node):
            new_node = ast.AsyncFunctionDef(
                self._visit(node.name),
                self._visit(node.args),
                self._visit(node.body),
                self._visit(node.decorator_list),
                self._visit(node.returns),
            )
            ast.copy_location(new_node, node)
            return new_node 
Example #12
Source File: compilation.py    From jishaku with MIT License 5 votes vote down vote up
def wrap_code(code: str, args: str = '') -> ast.Module:
    """
    Compiles Python code into an async function or generator,
    and automatically adds return if the function body is a single evaluation.
    Also adds inline import expression support.
    """

    user_code = import_expression.parse(code, mode='exec')
    mod = import_expression.parse(CORO_CODE.format(args), mode='exec')

    definition = mod.body[-1]  # async def ...:
    assert isinstance(definition, ast.AsyncFunctionDef)

    try_block = definition.body[-1]  # try:
    assert isinstance(try_block, ast.Try)

    try_block.body.extend(user_code.body)

    ast.fix_missing_locations(mod)

    KeywordTransformer().generic_visit(try_block)

    last_expr = try_block.body[-1]

    # if the last part isn't an expression, ignore it
    if not isinstance(last_expr, ast.Expr):
        return mod

    # if the last expression is not a yield
    if not isinstance(last_expr.value, ast.Yield):
        # copy the value of the expression into a yield
        yield_stmt = ast.Yield(last_expr.value)
        ast.copy_location(yield_stmt, last_expr)
        # place the yield into its own expression
        yield_expr = ast.Expr(yield_stmt)
        ast.copy_location(yield_expr, last_expr)

        # place the yield where the original expression was
        try_block.body[-1] = yield_expr

    return mod 
Example #13
Source File: compiler.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def visit_Global (self, node):
        self.getScope (ast.FunctionDef, ast.AsyncFunctionDef) .nonlocals.update (node.names)

        # raise utils.Error (
            # lineNr = self.lineNr,
            # message = '\n\tKeyword \'global\' not supported, use \'nonlocal\' instead, or make variable attribute of \'window\'\n'
        # ) 
Example #14
Source File: transformer_test.py    From pyt with GNU General Public License v2.0 5 votes vote down vote up
def test_async_removed_by_transformer(self):
        self.maxDiff = 99999
        async_tree = ast.parse("\n".join([
            "async def a():",
            "   async for b in c():",
            "       await b()",
            "   async with d() as e:",
            "       pass",
            "   return await y()"
        ]))
        self.assertIsInstance(async_tree.body[0], ast.AsyncFunctionDef)
        self.assertIsInstance(async_tree.body[0].body[-1], ast.Return)
        self.assertIsInstance(async_tree.body[0].body[-1].value, ast.Await)

        sync_tree = ast.parse("\n".join([
            "def a():",
            "   for b in c():",
            "       b()",
            "   with d() as e:",
            "       pass",
            "   return y()"
        ]))
        self.assertIsInstance(sync_tree.body[0], ast.FunctionDef)

        transformed = PytTransformer().visit(async_tree)
        self.assertIsInstance(transformed.body[0], ast.FunctionDef)

        self.assertEqual(ast.dump(transformed), ast.dump(sync_tree)) 
Example #15
Source File: compiler.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def visit_Yield (self, node):
        self.getScope (ast.FunctionDef, ast.AsyncFunctionDef) .containsYield = True
        self.emit ('yield')
        if (node.value != None):
            self.emit (' ')
            self.visit (node.value) 
Example #16
Source File: compiler.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def visit_YieldFrom (self, node):
        self.getScope (ast.FunctionDef, ast.AsyncFunctionDef) .containsYield = True
        self.emit ('yield* ')
        self.visit (node.value) 
Example #17
Source File: annotate.py    From pasta with Apache License 2.0 5 votes vote down vote up
def visit_FunctionDef(self, node):
    for i, decorator in enumerate(node.decorator_list):
      self.attr(node, 'decorator_symbol_%d' % i, [self.ws, '@', self.ws],
                default='@')
      self.visit(decorator)
      self.attr(node, 'decorator_suffix_%d' % i, [self.ws_oneline],
                default='\n' + self._indent)
    if (hasattr(ast, 'AsyncFunctionDef') and
        isinstance(node, ast.AsyncFunctionDef)):
      self.attr(node, 'function_def',
                [self.ws, 'async', self.ws, 'def', self.ws, node.name, self.ws],
                deps=('name',), default='async def %s' % node.name)
    else:
      self.attr(node, 'function_def',
                [self.ws, 'def', self.ws, node.name, self.ws],
                deps=('name',), default='def %s' % node.name)
    # In Python 3, there can be extra args in kwonlyargs
    kwonlyargs = getattr(node.args, 'kwonlyargs', [])
    args_count = sum((len(node.args.args + kwonlyargs),
                      1 if node.args.vararg else 0,
                      1 if node.args.kwarg else 0))
    with self.scope(node, 'args', trailing_comma=args_count > 0,
                    default_parens=True):
      self.visit(node.args)

    if getattr(node, 'returns', None):
      self.attr(node, 'returns_prefix', [self.ws, '->', self.ws],
                deps=('returns',), default=' -> ')
      self.visit(node.returns)

    self.attr(node, 'open_block', [self.ws, ':', self.ws_oneline],
              default=':\n')
    for stmt in self.indented(node, 'body'):
      self.visit(stmt) 
Example #18
Source File: loops.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_implicit_yield_from(self, node: AnyFor) -> None:
        if isinstance(nodes.get_context(node), ast.AsyncFunctionDef):
            # Python does not support 'yield from' inside async functions
            return

        is_implicit_yield_from = (
            len(node.body) == 1 and
            isinstance(node.body[0], ast.Expr) and
            isinstance(node.body[0].value, ast.Yield)
        )
        if is_implicit_yield_from:
            self.add_violation(ImplicitYieldFromViolation(node)) 
Example #19
Source File: classes.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_bound_methods(self, node: types.AnyFunctionDef) -> None:
        node_context = nodes.get_context(node)
        if not isinstance(node_context, ast.ClassDef):
            return

        if not functions.get_all_arguments(node):
            self.add_violation(
                oop.MethodWithoutArgumentsViolation(node, text=node.name),
            )

        if node.name in constants.MAGIC_METHODS_BLACKLIST:
            self.add_violation(
                oop.BadMagicMethodViolation(node, text=node.name),
            )

        is_async = isinstance(node, ast.AsyncFunctionDef)
        if is_async and access.is_magic(node.name):
            if node.name in constants.ASYNC_MAGIC_METHODS_BLACKLIST:
                self.add_violation(
                    oop.AsyncMagicMethodViolation(node, text=node.name),
                )

        self._check_useless_overwritten_methods(
            node,
            class_name=node_context.name,
        ) 
Example #20
Source File: enhancements.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def set_node_context(tree: ast.AST) -> ast.AST:
    """
    Used to set proper context to all nodes.

    What we call "a context"?
    Context is where exactly this node belongs on a global level.

    Example:
    .. code:: python

        if some_value > 2:
            test = 'passed'

    Despite the fact ``test`` variable has ``Assign`` as it parent
    it will have ``Module`` as a context.

    What contexts do we respect?

    - :py:class:`ast.Module`
    - :py:class:`ast.ClassDef`
    - :py:class:`ast.FunctionDef` and :py:class:`ast.AsyncFunctionDef`

    .. versionchanged:: 0.8.1

    """
    for statement in ast.walk(tree):
        current_context = _find_context(statement, _CONTEXTS)
        setattr(statement, 'wps_context', current_context)  # noqa: B010
    return tree 
Example #21
Source File: bugfixes.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def fix_async_offset(tree: ast.AST) -> ast.AST:
    """
    Fixes ``col_offest`` values for async nodes.

    This is a temporary check for async-based expressions, because offset
    for them isn't calculated properly. We can calculate right version
    of offset with subscripting ``6`` (length of "async " part).

    Affected ``python`` versions:

    - all versions below ``python3.6.7``

    Read more:
        https://bugs.python.org/issue29205
        https://github.com/wemake-services/wemake-python-styleguide/issues/282

    """
    nodes_to_fix = (
        ast.AsyncFor,
        ast.AsyncWith,
        ast.AsyncFunctionDef,
    )
    for node in ast.walk(tree):
        if isinstance(node, nodes_to_fix):
            error = 6 if node.col_offset % 4 else 0
            node.col_offset = node.col_offset - error
    return tree 
Example #22
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _get_return_type(fn):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> Optional[str]
    if fn.returns is not None and hasattr(fn.returns, 'id'):
        return getattr(fn.returns, 'id')
    return None 
Example #23
Source File: helper.py    From YAPyPy with MIT License 5 votes vote down vote up
def def_rewrite(mark: Tokenizer,
                name: Tokenizer,
                args: ast.arguments,
                ret: ast.AST,
                body: list,
                is_async: bool = False):
    name = name.value
    ty = ast.AsyncFunctionDef if is_async else ast.FunctionDef
    return ty(name, args, body, [], ret, **loc @ mark) 
Example #24
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _get_arguments(fn):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> Tuple[List[str], List[str]]  # noqa: E501
    arguments = list()  # type: List[str]
    types = list()  # type: List[str]

    def add_arg_by_name(name, arg):
        arguments.append(name)
        if arg.annotation is not None and hasattr(arg.annotation, 'id'):
            types.append(arg.annotation.id)
        else:
            types.append(None)

    for arg in fn.args.args:
        add_arg_by_name(arg.arg, arg)

    for arg in fn.args.kwonlyargs:
        add_arg_by_name(arg.arg, arg)

    # Handle single-star arguments.
    if fn.args.vararg is not None:
        name = '*' + fn.args.vararg.arg
        add_arg_by_name(name, fn.args.vararg)

    if fn.args.kwarg is not None:
        name = '**' + fn.args.kwarg.arg
        add_arg_by_name(name, fn.args.kwarg)

    return arguments, types 
Example #25
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _walk(fun, skip):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef], Callable) -> Iterator[ast.AST]  # noqa: E501
    """Walk through the nodes in this function, skipping as necessary.

    ast.walk goes through nodes in an arbitrary order, and doesn't
    allow you to skip an entire branch (as far as I know.)  This
    function will perform an in-order breadth-first traversal, and will
    skip unnecessary branches.

    Args:
        fun: The function to walk.
        skip: A function which returns True if we should skip the current
            node and all of its children.

    Yields:
        Children of the function and the function itself.

    """
    queue = deque()  # type: deque
    queue.appendleft(fun)
    while len(queue) > 0:
        curr = queue.pop()
        if skip(curr):
            continue
        if hasattr(curr, 'body'):
            queue.extendleft(curr.body)
        if hasattr(curr, 'handlers'):
            queue.extendleft(curr.handlers)
        if hasattr(curr, 'orelse'):
            queue.extendleft(curr.orelse)
        yield curr 
Example #26
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _has_yield(fun):  # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool  # noqa: E501
    for node in ast.walk(fun):
        if isinstance(node, ast.Yield) or isinstance(node, ast.YieldFrom):
            return True
    return False 
Example #27
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _get_all_functions(tree):  # type: (ast.AST) -> Iterator[Union[ast.FunctionDef, ast.AsyncFunctionDef]]  # noqa: E501
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef):
            yield node
        elif hasattr(ast, 'AsyncFunctionDef'):
            if isinstance(node, ast.AsyncFunctionDef):
                yield node 
Example #28
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _is_classmethod(fun):  # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool  # noqa: E501
    return 'classmethod' in _get_decorator_names(fun) 
Example #29
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _is_staticmethod(fun):  # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool  # noqa: E501
    return 'staticmethod' in _get_decorator_names(fun) 
Example #30
Source File: function_description.py    From darglint with MIT License 5 votes vote down vote up
def _get_stripped_method_args(method):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> Tuple[List[str], List[str]]  # noqa: E501
    args, types = _get_arguments(method)
    if 'cls' in args and _is_classmethod(method):
        args.remove('cls')
        types.pop(0)
    elif 'self' in args and not _is_staticmethod(method):
        args.remove('self')
        types.pop(0)
    return args, types