本文整理匯總了Python中astroid.If方法的典型用法代碼示例。如果您正苦於以下問題:Python astroid.If方法的具體用法?Python astroid.If怎麽用?Python astroid.If使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類astroid
的用法示例。
在下文中一共展示了astroid.If方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _if_statement_is_always_returning
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _if_statement_is_always_returning(if_node):
def _has_return_node(elems, scope):
for node in elems:
if isinstance(node, astroid.If):
yield _if_statement_is_always_returning(node)
elif isinstance(node, astroid.Return):
yield node.scope() is scope
scope = if_node.scope()
body_returns = _all_elements_are_true(
_has_return_node(if_node.body, scope=scope)
)
if if_node.orelse:
orelse_returns = _all_elements_are_true(
_has_return_node(if_node.orelse, scope=scope)
)
else:
orelse_returns = False
return body_returns and orelse_returns
示例2: _is_actual_elif
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _is_actual_elif(self, node):
"""Check if the given node is an actual elif
This is a problem we're having with the builtin ast module,
which splits `elif` branches into a separate if statement.
Unfortunately we need to know the exact type in certain
cases.
"""
if isinstance(node.parent, astroid.If):
orelse = node.parent.orelse
# current if node must directly follow a "else"
if orelse and orelse == [node]:
if (node.lineno, node.col_offset) in self._elifs:
return True
return False
示例3: visit_functiondef
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def visit_functiondef(self, node):
if not self.linter.is_message_enabled('wrong-import-position', node.fromlineno):
return
# If it is the first non import instruction of the module, record it.
if self._first_non_import_node:
return
# Check if the node belongs to an `If` or a `Try` block. If they
# contain imports, skip recording this node.
if not isinstance(node.parent.scope(), astroid.Module):
return
root = node
while not isinstance(root.parent, astroid.Module):
root = root.parent
if isinstance(root, (astroid.If, astroid.TryFinally, astroid.TryExcept)):
if any(root.nodes_of_class((astroid.Import, astroid.ImportFrom))):
return
self._first_non_import_node = node
示例4: _find_frame_imports
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _find_frame_imports(name, frame):
"""
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
"""
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imports:
for import_name, import_alias in import_node.names:
# If the import uses an alias, check only that.
# Otherwise, check only the import name.
if import_alias:
if import_alias == name:
return True
elif import_name and import_name == name:
return True
return None
示例5: visit_functiondef
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def visit_functiondef(self, node):
if node.is_method():
if node.name in self._unused_magic_methods:
method_name = node.name
if node.name.startswith("__"):
method_name = node.name[2:-2]
self.add_message(method_name + "-method", node=node)
elif node.name == "next":
# If there is a method named `next` declared, if it is invokable
# with zero arguments then it implements the Iterator protocol.
# This means if the method is an instance method or a
# classmethod 1 argument should cause a failure, if it is a
# staticmethod 0 arguments should cause a failure.
failing_arg_count = 1
if utils.decorated_with(node, [bases.BUILTINS + ".staticmethod"]):
failing_arg_count = 0
if len(node.args.args) == failing_arg_count:
self.add_message("next-method-defined", node=node)
示例6: visit_functiondef
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def visit_functiondef(self, node):
if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno):
return
# If it is the first non import instruction of the module, record it.
if self._first_non_import_node:
return
# Check if the node belongs to an `If` or a `Try` block. If they
# contain imports, skip recording this node.
if not isinstance(node.parent.scope(), astroid.Module):
return
root = node
while not isinstance(root.parent, astroid.Module):
root = root.parent
if isinstance(root, (astroid.If, astroid.TryFinally, astroid.TryExcept)):
if any(root.nodes_of_class((astroid.Import, astroid.ImportFrom))):
return
self._first_non_import_node = node
示例7: node_type
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
"""Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
"""
# check there is only one possible type for the assign node. Else we
# don't handle it for now
types = set()
try:
for var_type in node.infer():
if var_type == astroid.Uninferable or is_none(var_type):
continue
types.add(var_type)
if len(types) > 1:
return None
except astroid.InferenceError:
return None
return types.pop() if types else None
示例8: visit_if
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def visit_if(self, node):
if isinstance(node.parent, astroid.If):
orelse = node.parent.orelse
# current if node must directly follow a "else"
if orelse and orelse == [node]:
if not self._elifs[self._if_counter]:
self.add_message('else-if-used', node=node)
self._if_counter += 1
示例9: _check_and_add_messages
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _check_and_add_messages(self):
assigns = self._assigns.pop()
for name, args in assigns.items():
if len(args) <= 1:
continue
orig_node, orig_type = args[0]
# Check if there is a type in the following nodes that would be
# different from orig_type.
for redef_node, redef_type in args[1:]:
if redef_type == orig_type:
continue
# if a variable is defined to several types in a if node,
# this is not actually redefining.
orig_parent = orig_node.parent
redef_parent = redef_node.parent
if isinstance(orig_parent, astroid.If):
if orig_parent == redef_parent:
if (redef_node in orig_parent.orelse and
orig_node not in orig_parent.orelse):
orig_node, orig_type = redef_node, redef_type
continue
elif (isinstance(redef_parent, astroid.If) and
redef_parent in orig_parent.nodes_of_class(astroid.If)):
orig_node, orig_type = redef_node, redef_type
continue
orig_type = orig_type.replace(BUILTINS + ".", '')
redef_type = redef_type.replace(BUILTINS + ".", '')
self.add_message('redefined-variable-type', node=redef_node,
args=(name, orig_type, redef_type))
break
示例10: visit_if
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def visit_if(self, node):
"""increments the branches counter and checks boolean expressions"""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (len(node.orelse) > 1 or
not isinstance(node.orelse[0], If)):
branches += 1
self._inc_branch(node, branches)
self._stmts += branches
示例11: _node_is_test_condition
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _node_is_test_condition(node):
""" Checks if node is an if, while, assert or if expression statement."""
return isinstance(node, (astroid.If, astroid.While, astroid.Assert, astroid.IfExp))
示例12: is_trailing_comma
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def is_trailing_comma(tokens, index):
"""Check if the given token is a trailing comma
:param tokens: Sequence of modules tokens
:type tokens: list[tokenize.TokenInfo]
:param int index: Index of token under check in tokens
:returns: True if the token is a comma which trails an expression
:rtype: bool
"""
token = tokens[index]
if token.exact_type != tokenize.COMMA:
return False
# Must have remaining tokens on the same line such as NEWLINE
left_tokens = itertools.islice(tokens, index + 1, None)
same_line_remaining_tokens = list(itertools.takewhile(
lambda other_token, _token=token: other_token.start[0] == _token.start[0],
left_tokens
))
# Note: If the newline is tokenize.NEWLINE and not tokenize.NL
# then the newline denotes the end of expression
is_last_element = all(
other_token.type in (tokenize.NEWLINE, tokenize.COMMENT)
for other_token in same_line_remaining_tokens
)
if not same_line_remaining_tokens or not is_last_element:
return False
def get_curline_index_start():
"""Get the index denoting the start of the current line"""
for subindex, token in enumerate(reversed(tokens[:index])):
# See Lib/tokenize.py and Lib/token.py in cpython for more info
if token.type in (tokenize.NEWLINE, tokenize.NL):
return index - subindex
return 0
curline_start = get_curline_index_start()
for prevtoken in tokens[curline_start:index]:
if '=' in prevtoken.string:
return True
return False
示例13: _in_iterating_context
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _in_iterating_context(node):
"""Check if the node is being used as an iterator.
Definition is taken from lib2to3.fixer_util.in_special_context().
"""
parent = node.parent
# Since a call can't be the loop variant we only need to know if the node's
# parent is a 'for' loop to know it's being used as the iterator for the
# loop.
if isinstance(parent, astroid.For):
return True
# Need to make sure the use of the node is in the iterator part of the
# comprehension.
if isinstance(parent, astroid.Comprehension):
if parent.iter == node:
return True
# Various built-ins can take in an iterable or list and lead to the same
# value.
elif isinstance(parent, astroid.Call):
if isinstance(parent.func, astroid.Name):
parent_scope = parent.func.lookup(parent.func.name)[0]
if _is_builtin(parent_scope) and parent.func.name in _ACCEPTS_ITERATOR:
return True
elif isinstance(parent.func, astroid.Attribute):
if parent.func.attrname == 'join':
return True
# If the call is in an unpacking, there's no need to warn,
# since it can be considered iterating.
elif (isinstance(parent, astroid.Assign) and
isinstance(parent.targets[0], (astroid.List, astroid.Tuple))):
if len(parent.targets[0].elts) > 1:
return True
return False
示例14: _is_conditional_import
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def _is_conditional_import(node):
"""Checks if an import node is in the context of a conditional.
"""
parent = node.parent
return isinstance(parent, (astroid.TryExcept, astroid.ExceptHandler,
astroid.If, astroid.IfExp))
示例15: test_subscript_load_ctx
# 需要導入模塊: import astroid [as 別名]
# 或者: from astroid import If [as 別名]
def test_subscript_load_ctx(node):
"""Test visitor of Subscript node when loaded in an (if) expression."""
load_node = astroid.If()
load_node.postinit(astroid.Const(True), [node], [])
module, _ = cs._parse_text(load_node)
for subscript_node in module.nodes_of_class(astroid.Subscript):
list_node = subscript_node.value
assert subscript_node.inf_type.getValue() == List[list_node.elts[0].inf_type.getValue()]