本文整理汇总了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()
示例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)
示例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
示例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)
示例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
示例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
示例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()
示例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)
示例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))
示例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
)
示例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),
),
)
示例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])
示例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))
示例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')
示例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)