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


Python ast.NameConstant方法代碼示例

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


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

示例1: convert_to_value

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [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

示例2: _get_value_from_ast

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [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

示例3: has_shell

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def has_shell(context):
    keywords = context.node.keywords
    result = False
    if 'shell' in context.call_keywords:
        for key in keywords:
            if key.arg == 'shell':
                val = key.value
                if isinstance(val, ast.Num):
                    result = bool(val.n)
                elif isinstance(val, ast.List):
                    result = bool(val.elts)
                elif isinstance(val, ast.Dict):
                    result = bool(val.keys)
                elif isinstance(val, ast.Name) and val.id in ['False', 'None']:
                    result = False
                elif not six.PY2 and isinstance(val, ast.NameConstant):
                    result = val.value
                else:
                    result = True
    return result 
開發者ID:PyCQA,項目名稱:bandit,代碼行數:22,代碼來源:injection_shell.py

示例4: stringify_node

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def stringify_node(self, node: Any) -> str:
        if hasattr(node, 'first_token') and hasattr(node, 'last_token'):
            return self.code[node.first_token.startpos:node.last_token.endpos]

        if isinstance(node, ast.NameConstant):
            return str(node.value)
        if isinstance(node, ast.Str):
            return "'" + node.s.replace("'", "''") + "'"
        if isinstance(node, ast.Num):
            return str(node.n)
        if isinstance(node, ast.BinOp):
            left = self.stringify_node(node.left)
            right = self.stringify_node(node.right)
            op = self.stringify_operation(node.op)
            return f'{left} {op} {right}'

        return str(node) 
開發者ID:LexPredict,項目名稱:lexpredict-contraxsuite,代碼行數:19,代碼來源:expressions.py

示例5: visit_Assign

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def visit_Assign(self, node):

        try:
            left_side = node.targets[0]

                    #do not handle attribute assignments
            if isinstance(left_side,ast.Attribute):
                return

            # Handle the NamedConstant type that is only present in Python 3
            astTypes = [ast.Num, ast.Str, ast.Name]
            if hasattr(ast, 'NameConstant'):
                astTypes.append(ast.NameConstant)

            if type(node.value) in astTypes:
                self.handle_assignment(left_side.id, node.value)
            elif type(node.value) == ast.Tuple:
                # we have a multi-value assignment
                for n, v in zip(left_side.elts, node.value.elts):
                    self.handle_assignment(n.id, v)
        except:
            traceback.print_exc()
            print("Unable to handle assignment for node '%s'" % ast.dump(left_side))

        return node 
開發者ID:jmwright,項目名稱:cadquery-freecad-module,代碼行數:27,代碼來源:cqgi.py

示例6: get_type

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def get_type(expr):
  """Find the type of an expression.

  Args:
    expr: The expression to check.

  Returns:
    The type of the expression.
  """
  if isinstance(expr, ast.Num):
    return build_pb2.Attribute.INTEGER
  elif isinstance(expr, ast.Str):
    return build_pb2.Attribute.STRING
  elif isinstance(expr, ast.List):
    return build_pb2.Attribute.STRING_LIST
  elif isinstance(expr, ast.Name) and (expr.id == "True" or expr.id == "False"):
    return build_pb2.Attribute.BOOLEAN
  elif hasattr(ast, 'NameConstant') and isinstance(expr, ast.NameConstant) and (expr.value == True or expr.value == False):
    return build_pb2.Attribute.BOOLEAN
  else:
    return build_pb2.Attribute.UNKNOWN 
開發者ID:bazelbuild,項目名稱:skydoc,代碼行數:23,代碼來源:macro_extractor.py

示例7: convert_to_value

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [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 PY33) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
開發者ID:zrzka,項目名稱:blackmamba,代碼行數:27,代碼來源:checker.py

示例8: _make_expr_build_slice

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def _make_expr_build_slice(toplevel, stack_builders):
    # Arg is always either 2 or 3.  If it's 3, then the first expression is the
    # step value.
    if toplevel.arg == 3:
        step = make_expr(stack_builders)
    else:
        step = None

    def normalize_empty_slice(node):
        """
        Convert LOAD_CONST(None) to just None.

        This normalizes slices of the form a[b:None] to just a[b:].
        """
        if isinstance(node, ast.NameConstant) and node.value is None:
            return None
        return node

    upper = normalize_empty_slice(make_expr(stack_builders))
    lower = normalize_empty_slice(make_expr(stack_builders))

    return ast.Slice(lower=lower, upper=upper, step=step) 
開發者ID:llllllllll,項目名稱:codetransformer,代碼行數:24,代碼來源:_343.py

示例9: get_ty

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def get_ty(self, annotation) -> ir.Typ:
        """ Get the type based on type annotation """
        if isinstance(annotation, type):
            type_name = annotation.__name__
        elif annotation is None:
            return
        else:
            if (
                isinstance(annotation, ast.NameConstant)
                and annotation.value is None
            ):
                return
            type_name = annotation.id

        if type_name in self.type_mapping:
            return self.type_mapping[type_name]
        else:
            self.error(annotation, "Unhandled type: {}".format(type_name)) 
開發者ID:windelbouwman,項目名稱:ppci,代碼行數:20,代碼來源:python2ir.py

示例10: kwarg_primitive

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def kwarg_primitive(call, kwarg_name, primitive):
    try:
        # Python 3
        primitive_type = ast.NameConstant

        def comparator(keyword, inner_primitive):
            return (
                isinstance(keyword.value, primitive_type)
                and keyword.value.value == inner_primitive
            )
    except AttributeError:
        # Python 2, AttributeError on ast.NameConstant
        primitive_type = ast.Name

        def comparator(keyword, inner_primitive):
            return (
                isinstance(keyword.value, primitive_type)
                and keyword.value.id == str(inner_primitive)
            )

    return any(
        keyword.arg == kwarg_name
        and comparator(keyword, primitive)
        for keyword in call.keywords
    ) 
開發者ID:duo-labs,項目名稱:dlint,代碼行數:27,代碼來源:tree.py

示例11: _check_boolean_arguments

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def _check_boolean_arguments(self, node: ast.Call) -> None:
        if len(node.args) == 1 and not node.keywords:
            return  # Calls with single boolean argument are allowed

        for arg in node.args:
            if not isinstance(arg, ast.NameConstant):
                continue

            is_ignored = self._is_call_ignored(node)

            # We do not check for `None` values here:
            if not is_ignored and arg.value in {True, False}:
                self.add_violation(
                    BooleanPositionalArgumentViolation(
                        arg, text=str(arg.value),
                    ),
                ) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:19,代碼來源:functions.py

示例12: _is_simplifiable_assign

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def _is_simplifiable_assign(
        self,
        node_body: List[ast.stmt],
    ) -> Optional[str]:
        wrong_length = len(node_body) != 1
        if wrong_length or not isinstance(node_body[0], AssignNodes):
            return None
        if not isinstance(node_body[0].value, ast.NameConstant):
            return None
        if node_body[0].value.value is None:
            return None

        targets = get_assign_targets(node_body[0])
        if len(targets) != 1:
            return None

        return source.node_to_string(targets[0]) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:19,代碼來源:compares.py

示例13: _check_last_return_in_function

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def _check_last_return_in_function(self, node: ast.Return) -> None:
        parent = get_parent(node)
        if not isinstance(parent, FunctionNodes):
            return

        returns = len(tuple(filter(
            lambda return_node: return_node.value is not None,
            walk.get_subnodes_by_type(parent, ast.Return),
        )))

        last_value_return = (
            len(parent.body) > 1 and
            returns < 2 and
            isinstance(node.value, ast.NameConstant) and
            node.value.value is None
        )

        one_return_with_none = (
            returns == 1 and
            isinstance(node.value, ast.NameConstant) and
            node.value.value is None
        )

        if node.value is None or last_value_return or one_return_with_none:
            self.add_violation(InconsistentReturnViolation(node)) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:27,代碼來源:keywords.py

示例14: check_fillable_node

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def check_fillable_node(node, path):
    if isinstance(node, (ast.Num, ast.Str)):
        return
    elif isinstance(node, ast.NameConstant) and (node.value in (True, False)):
        return
    elif isinstance(node, ast.List):
        for n in node.elts:
            check_fillable_node(n, path)
        return
    elif isinstance(node, ast.Dict):
        for n in node.keys:
            check_fillable_node(n, path)
        for n in node.values:
            check_fillable_node(n, path)
        return
    
    raise astcheck.ASTMismatch(path, node, 'number, string or boolean') 
開發者ID:takluyver,項目名稱:nbparameterise,代碼行數:19,代碼來源:python.py

示例15: visit_NameConstant

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import NameConstant [as 別名]
def visit_NameConstant(self, node: ast.NameConstant) -> None:
        # True, False, None
        print(f"NameConstant: {node}")
        print(ast.dump(node))
        self.generic_visit(node) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:7,代碼來源:_devtools.py


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