當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.Str方法代碼示例

本文整理匯總了Python中ast.Str方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.Str方法的具體用法?Python ast.Str怎麽用?Python ast.Str使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.Str方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: version

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def version():
    path = 'pypika/__init__.py'
    with open(path, 'r') as file:
        t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST)
        for node in (n for n in t.body if isinstance(n, ast.Assign)):
            if len(node.targets) == 1:
                name = node.targets[0]
                if isinstance(name, ast.Name) and \
                      name.id in ('__version__', '__version_info__', 'VERSION'):
                    v = node.value
                    if isinstance(v, ast.Str):
                        return v.s

                    if isinstance(v, ast.Tuple):
                        r = []
                        for e in v.elts:
                            if isinstance(e, ast.Str):
                                r.append(e.s)
                            elif isinstance(e, ast.Num):
                                r.append(str(e.n))
                        return '.'.join(r) 
開發者ID:kayak,項目名稱:pypika,代碼行數:23,代碼來源:setup.py

示例2: visit_FunctionDef

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def visit_FunctionDef(self, node):
        self.refStack.push()
        for n in node.body:
            self.visit(n)
        self.tree.kind = _kind.SIMPLE_ALWAYS_COMB
        for n in node.body:
            if isinstance(n, ast.Expr) and isinstance(n.value, ast.Str):
                continue  # skip doc strings
            if isinstance(n, ast.Assign) and \
               isinstance(n.targets[0], ast.Attribute) and \
               self.getKind(n.targets[0].value) != _kind.REG:
                pass
            else:
                self.tree.kind = _kind.ALWAYS_COMB
                return
        # rom access is expanded into a case statement in addition
        # to any always_comb that contains a list of signals
        # if self.tree.hasRom or self.tree.hasLos:
        if self.tree.hasRom:
            self.tree.kind = _kind.ALWAYS_COMB
        self.refStack.pop() 
開發者ID:myhdl,項目名稱:myhdl,代碼行數:23,代碼來源:_analyze.py

示例3: stateful_wait_for

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def stateful_wait_for(self, call):
        if isinstance(call.func, ast.Attribute):
            if call.func.attr in ['wait_for_message', 'wait_for_reaction']:
                event = call.func.attr.split('_')[2]
                event = 'message' if event == 'message' else 'reaction_add'
                call.func.attr = 'wait_for'
                if call.args:
                    timeout = call.args[0]
                    call.args = []
                    call.keywords.append(ast.keyword(arg='timeout', value=timeout))

                call.args.insert(0, ast.Str(s=event))
                for kw in list(call.keywords):
                    if kw.arg != 'check' and kw.arg != 'timeout':
                        call.keywords.remove(kw)
                        warnings.warn('wait_for keyword breaking change detected. Rewrite removes the {} keyword'
                                      ' from wait_for.'.format(kw.arg))
                    elif kw.arg == 'timeout':
                        warnings.warn('wait_for timeout breaking change detected. Timeouts now raise '
                                      'asyncio.TimeoutError instead of returning None.')

                stats_counter['call_changes'] += 1
        return call 
開發者ID:tylergibbs2,項目名稱:async2rewrite,代碼行數:25,代碼來源:transformers.py

示例4: convert_to_value

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def convert_to_value(item):
    if isinstance(item, ast.Str):
        return item.s
    elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
        return item.s
    elif isinstance(item, ast.Tuple):
        return tuple(convert_to_value(i) for i in item.elts)
    elif isinstance(item, ast.Num):
        return item.n
    elif isinstance(item, ast.Name):
        result = VariableKey(item=item)
        constants_lookup = {
            'True': True,
            'False': False,
            'None': None,
        }
        return constants_lookup.get(
            result.name,
            result,
        )
    elif (not PY2) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:27,代碼來源:checker.py

示例5: _get_value_from_ast

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def _get_value_from_ast(self, obj):
        """
        Return the value of the ast object.
        """
        if isinstance(obj, ast.Num):
            return obj.n
        elif isinstance(obj, ast.Str):
            return obj.s
        elif isinstance(obj, ast.List):
            return [self._get_value_from_ast(e) for e in obj.elts]
        elif isinstance(obj, ast.Tuple):
            return tuple([self._get_value_from_ast(e) for e in obj.elts])

        # None, True and False are NameConstants in Py3.4 and above.
        elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
            return obj.value

        # For python versions below 3.4
        elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
            return string_to_constant[obj.id]

        # Probably passed a variable name.
        # Or passed a single word without wrapping it in quotes as an argument
        # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
        raise NameError("name '%s' is not defined" % obj.id) 
開發者ID:bids-standard,項目名稱:pybids,代碼行數:27,代碼來源:inflect.py

示例6: pop_format_context

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def pop_format_context(self, expl_expr):
        """Format the %-formatted string with current format context.

        The expl_expr should be an ast.Str instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .expl_stmts and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        if self.enable_assertion_pass_hook:
            self.format_variables.append(name)
        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:22,代碼來源:rewrite.py

示例7: atomic_type_literal_ast_to_ir2

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def atomic_type_literal_ast_to_ir2(ast_node: ast.Call,
                                   compilation_context: CompilationContext,
                                   in_match_pattern: bool,
                                   check_var_reference: Callable[[ast.Name], None],
                                   match_lambda_argument_names: Set[str]):
    if ast_node.keywords:
        raise CompilationError(compilation_context, ast_node.keywords[0].value,
                               'Keyword arguments are not supported in Type()')

    if len(ast_node.args) != 1:
        raise CompilationError(compilation_context, ast_node, 'Type() takes 1 argument. Got: %s' % len(ast_node.args))
    [arg] = ast_node.args
    if not isinstance(arg, ast.Str):
        raise CompilationError(compilation_context, arg, 'The argument passed to Type should be a string constant.')
    _check_atomic_type(arg, compilation_context)
    return ir2.AtomicTypeLiteral(cpp_type=arg.s) 
開發者ID:google,項目名稱:tmppy,代碼行數:18,代碼來源:_ast_to_ir2.py

示例8: test_dump

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def test_dump(self):
        node = ast.parse('spam(eggs, "and cheese")')
        self.assertEqual(ast.dump(node),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
            "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
            "keywords=[], starargs=None, kwargs=None))])"
        )
        self.assertEqual(ast.dump(node, annotate_fields=False),
            "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
            "Str('and cheese')], [], None, None))])"
        )
        self.assertEqual(ast.dump(node, include_attributes=True),
            "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
            "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
            "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
            "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
            "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
        ) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:20,代碼來源:test_ast.py

示例9: test_nodeclasses

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def test_nodeclasses(self):
        # IronPyhon performs argument typechecking
        l=ast.Str('A')
        o=ast.Mult()
        r=ast.Num('13')
        x=ast.BinOp(l,o,r,lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, l, o)

        # can set attributes through kwargs too
        x = ast.BinOp(left=l, op=o, right=r, lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:25,代碼來源:test_ast.py

示例10: test_attributes

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def test_attributes(self):
        # assert True, "bad"
        assert0 = ast.Assert()
        self.assertFalse(hasattr(assert0, 'lineno'))
        self.assertFalse(hasattr(assert0, 'col_offset'))
        assert1 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'))
        self.assertFalse(hasattr(assert1, 'lineno'))
        self.assertFalse(hasattr(assert1, 'col_offset'))
        try:
            tmp=assert1.lineno
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        try:
            tmp=assert1.col_offset
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        assert2 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'),2,3)
        self.assertEqual(assert2.lineno,2)
        self.assertEqual(assert2.col_offset,3) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:21,代碼來源:test_ast.py

示例11: visit_Hook

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def visit_Hook(self, node: parsing.Hook) -> ast.expr:
        """Generates python code calling a hook.

        self.evalHook('hookname', self.ruleNodes[-1])
        """
        return ast.Call(
            ast.Attribute(
                ast.Name('self', ast.Load()), 'evalHook', ast.Load()),
            [
                ast.Str(node.name),
                ast.Subscript(
                    ast.Attribute(
                        ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()),
                    ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))),
                    ast.Load())],
            [],
            None,
            None) 
開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:20,代碼來源:topython.py

示例12: visit_Call

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def visit_Call(self, node):
        def visit_func(node):
            if type(node) == ast.Name:
                return node.id
            elif type(node) == ast.Attribute:
                # Recursion on series of calls to attributes.
                func_name = visit_func(node.value)
                func_name += "." + node.attr
                return func_name
            elif type(node) == ast.Str:
                return node.s
            elif type(node) == ast.Subscript:
                return node.value.id

        func = node.func
        func_name = visit_func(func)
        self.current_block.func_calls.append(func_name) 
開發者ID:coetaur0,項目名稱:staticfg,代碼行數:19,代碼來源:builder.py

示例13: make_annotation

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def make_annotation(node=None, buffer='outside', content=None, cell_type='code', lineno=None):
    """Return a ast.Expr that looks like

    ```
    __cell__('make-cell', [content, buffer, cell_type])
    ```

    """
    content = astor.to_source(node).strip() if node else content
    lineno = str(node.lineno) if hasattr(node, 'lineno') else str(-1) if not lineno else str(lineno)
    call = ast.Call(
        func=ast.Name(id='__cell__', ctx=ast.Load()),
        args=[
            ast.Str(s=content),
            ast.Str(s=f'{buffer}'),
            ast.Str(s=cell_type),
            ast.Str(s=lineno),
        ],
        keywords=[]
    )
    return ast.Expr(call) 
開發者ID:ebanner,項目名稱:pynt,代碼行數:23,代碼來源:node_transformers.py

示例14: visit_Return

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def visit_Return(self, return_):
        """Convert returns into assignment/exception pairs

        Since the body of this function will be in the global namespace we
        can't have any returns. An acceptable alternative is to set a variable
        called 'RETURN' and then immediately raise an exception.

        >>> self = NamespacePromoter(buffer='foo')
        >>> code = '''
        ...
        ... return 5
        ...
        ... '''
        >>> tree = ast.parse(code)
        >>> return_, = tree.body

        """
        nodes = [
            ast.Assign(targets=[ast.Name(id='RETURN', ctx=ast.Store())], value=return_.value, lineno=return_.lineno),
            ast.Raise(exc=ast.Call(func=ast.Name(id='Exception', ctx=ast.Load()), args=[ast.Str(s='return')], keywords=[]), cause=None),
        ]
        return nodes 
開發者ID:ebanner,項目名稱:pynt,代碼行數:24,代碼來源:node_transformers.py

示例15: _format_tree

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Str [as 別名]
def _format_tree(self, tree, source, io):
        offset = 0
        chunks = []

        nodes = [n for n in ast.walk(tree)]

        displayed_nodes = []

        for node in nodes:
            nodecls = node.__class__
            nodename = nodecls.__name__

            if "col_offset" not in dir(node):
                continue

            if nodecls in self.AST_ELEMENTS["keywords"]:
                displayed_nodes.append((node, nodename.lower(), "keyword"))
            elif nodecls == ast.Name and node.id in self.AST_ELEMENTS["builtins"]:
                displayed_nodes.append((node, node.id, "builtin"))
            elif nodecls == ast.Str:
                displayed_nodes.append((node, "'{}'".format(node.s), "literal"))
            elif nodecls == ast.Num:
                displayed_nodes.append((node, str(node.n), "literal"))

        displayed_nodes.sort(key=lambda elem: elem[0].col_offset)

        for dn in displayed_nodes:
            node = dn[0]
            s = dn[1]
            theme = dn[2]

            begin_col = node.col_offset

            src_chunk = source[offset:begin_col]
            chunks.append(src_chunk)
            chunks.append(io.format("{}{}</>".format(self.THEME[theme], s)))
            offset = begin_col + len(s)

        chunks.append(source[offset:])

        return "".join(chunks) 
開發者ID:sdispater,項目名稱:clikit,代碼行數:43,代碼來源:exception_trace.py


注:本文中的ast.Str方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。