本文整理汇总了Python中pylint.checkers.utils.safe_infer函数的典型用法代码示例。如果您正苦于以下问题:Python safe_infer函数的具体用法?Python safe_infer怎么用?Python safe_infer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了safe_infer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _check_cmp_argument
def _check_cmp_argument(self, node):
# Check that the `cmp` argument is used
kwargs = []
if (isinstance(node.func, astroid.Attribute)
and node.func.attrname == 'sort'):
inferred = utils.safe_infer(node.func.expr)
if not inferred:
return
builtins_list = "{}.list".format(bases.BUILTINS)
if (isinstance(inferred, astroid.List)
or inferred.qname() == builtins_list):
kwargs = node.keywords
elif (isinstance(node.func, astroid.Name)
and node.func.name == 'sorted'):
inferred = utils.safe_infer(node.func)
if not inferred:
return
builtins_sorted = "{}.sorted".format(bases.BUILTINS)
if inferred.qname() == builtins_sorted:
kwargs = node.keywords
for kwarg in kwargs or []:
if kwarg.arg == 'cmp':
self.add_message('using-cmp-argument', node=node)
return
示例2: get_constant_values
def get_constant_values(self, node, key):
try:
ass = node.locals[key][-1]
except KeyError:
return
try:
xs = safe_infer(ass).get_children()
except AttributeError:
return
return [(x, x.value) for x in xs if isinstance(safe_infer(x), astng.Const)]
示例3: visit_callfunc
def visit_callfunc(self, node):
func = utils.safe_infer(node.func)
if (isinstance(func, astroid.BoundMethod)
and isinstance(func.bound, astroid.Instance)
and func.bound.name in ('str', 'unicode', 'bytes')
and func.name in ('strip', 'lstrip', 'rstrip')
and node.args):
arg = utils.safe_infer(node.args[0])
if not isinstance(arg, astroid.Const):
return
if len(arg.value) != len(set(arg.value)):
self.add_message('bad-str-strip-call', node=node,
args=(func.bound.name, func.name))
示例4: visit_callfunc
def visit_callfunc(self, node):
func = utils.safe_infer(node.func)
if (
isinstance(func, astroid.BoundMethod)
and isinstance(func.bound, astroid.Instance)
and func.bound.name in ("str", "unicode", "bytes")
and func.name in ("strip", "lstrip", "rstrip")
and node.args
):
arg = utils.safe_infer(node.args[0])
if not isinstance(arg, astroid.Const):
return
if len(arg.value) != len(set(arg.value)):
self.add_message("E1310", node=node, args=(func.bound.name, func.name))
示例5: possible_exc_types
def possible_exc_types(node):
"""
Gets all of the possible raised exception types for the given raise node.
.. note::
Caught exception types are ignored.
:param node: The raise node to find exception types for.
:type node: astroid.node_classes.NodeNG
:returns: A list of exception types possibly raised by :param:`node`.
:rtype: list(str)
"""
excs = []
if isinstance(node.exc, astroid.Name):
inferred = safe_infer(node.exc)
if inferred:
excs = [inferred.name]
elif (isinstance(node.exc, astroid.Call) and
isinstance(node.exc.func, astroid.Name)):
target = safe_infer(node.exc.func)
if isinstance(target, astroid.ClassDef):
excs = [target.name]
elif isinstance(target, astroid.FunctionDef):
for ret in target.nodes_of_class(astroid.Return):
if ret.frame() != target:
# return from inner function - ignore it
continue
val = safe_infer(ret.value)
if (val and isinstance(val, (astroid.Instance, astroid.ClassDef))
and inherit_from_std_ex(val)):
excs.append(val.name)
elif node.exc is None:
handler = node.parent
while handler and not isinstance(handler, astroid.ExceptHandler):
handler = handler.parent
if handler and handler.type:
inferred_excs = astroid.unpack_infer(handler.type)
excs = (exc.name for exc in inferred_excs
if exc is not astroid.Uninferable)
try:
return set(exc for exc in excs if not node_ignores_exception(node, exc))
except astroid.InferenceError:
return ()
示例6: _check_try_except_raise
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(handler):
exceptions = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, astroid.Tuple):
exceptions = {
exception
for exception in exceptions_in_handler.elts
if isinstance(exception, astroid.Name)
}
elif exceptions_in_handler:
exceptions = [exceptions_in_handler]
return exceptions
bare_raise = False
handler_having_bare_raise = None
excs_in_bare_handler = []
for handler in node.handlers:
if bare_raise:
# check that subsequent handler is not parent of handler which had bare raise.
# since utils.safe_infer can fail for bare except, check it before.
# also break early if bare except is followed by bare except.
excs_in_current_handler = gather_exceptions_from_handler(handler)
if not excs_in_current_handler:
bare_raise = False
break
for exc_in_current_handler in excs_in_current_handler:
inferred_current = utils.safe_infer(exc_in_current_handler)
if any(
utils.is_subclass_of(
utils.safe_infer(exc_in_bare_handler), inferred_current
)
for exc_in_bare_handler in excs_in_bare_handler
):
bare_raise = False
break
# `raise` as the first operator inside the except handler
if _is_raising([handler.body[0]]):
# flags when there is a bare raise
if handler.body[0].exc is None:
bare_raise = True
handler_having_bare_raise = handler
excs_in_bare_handler = gather_exceptions_from_handler(handler)
if bare_raise:
self.add_message("try-except-raise", node=handler_having_bare_raise)
示例7: visit_slice
def visit_slice(self, node):
# Check the type of each part of the slice
for index in (node.lower, node.upper, node.step):
if index is None:
continue
index_type = safe_infer(index)
if index_type is None or index_type is astroid.YES:
continue
# Constants must of type int or None
if isinstance(index_type, astroid.Const):
if isinstance(index_type.value, (int, type(None))):
continue
# Instance values must be of type int, None or an object
# with __index__
elif isinstance(index_type, astroid.Instance):
if index_type.pytype() in (BUILTINS + '.int',
BUILTINS + '.NoneType'):
continue
try:
index_type.getattr('__index__')
return
except astroid.NotFoundError:
pass
# Anything else is an error
self.add_message('invalid-slice-index', node=node)
示例8: _determine_function_name_type
def _determine_function_name_type(node):
"""Determine the name type whose regex the a function's name should match.
:param node: A function node.
:returns: One of ('function', 'method', 'attr')
"""
if not node.is_method():
return 'function'
if node.decorators:
decorators = node.decorators.nodes
else:
decorators = []
for decorator in decorators:
# If the function is a property (decorated with @property
# or @abc.abstractproperty), the name type is 'attr'.
if (isinstance(decorator, astroid.Name) or
(isinstance(decorator, astroid.Getattr) and
decorator.attrname == 'abstractproperty')):
infered = safe_infer(decorator)
if infered and infered.qname() in PROPERTY_CLASSES:
return 'attr'
# If the function is decorated using the prop_method.{setter,getter}
# form, treat it like an attribute as well.
elif (isinstance(decorator, astroid.Getattr) and
decorator.attrname in ('setter', 'deleter')):
return 'attr'
return 'method'
示例9: visit_asyncwith
def visit_asyncwith(self, node):
for ctx_mgr, _ in node.items:
inferred = checker_utils.safe_infer(ctx_mgr)
if inferred is None or inferred is astroid.Uninferable:
continue
if isinstance(inferred, bases.AsyncGenerator):
# Check if we are dealing with a function decorated
# with contextlib.asynccontextmanager.
if decorated_with(inferred.parent, self._async_generators):
continue
else:
try:
inferred.getattr("__aenter__")
inferred.getattr("__aexit__")
except exceptions.NotFoundError:
if isinstance(inferred, astroid.Instance):
# If we do not know the bases of this class,
# just skip it.
if not checker_utils.has_known_bases(inferred):
continue
# Just ignore mixin classes.
if self._ignore_mixin_members:
if inferred.name[-5:].lower() == "mixin":
continue
else:
continue
self.add_message(
"not-async-context-manager", node=node, args=(inferred.name,)
)
示例10: nodeisinstance
def nodeisinstance(node, klasses, check_base_classes=True):
if not isinstance(node, astng.Class):
return False
for base in node.bases:
val = safe_infer(base)
if not val:
continue
if type(val).__name__ == '_Yes':
continue
nodes = [val]
if check_base_classes:
try:
nodes = chain([val], val.ancestors())
except TypeError:
pass
for node in nodes:
qual = '%s.%s' % (node.root().name, node.name)
if qual in klasses:
return True
return False
示例11: _check_open_encoding
def _check_open_encoding(self, node):
"""Check that an open() call always has an encoding set."""
try:
mode_arg = utils.get_argument_from_call(node, position=1,
keyword='mode')
except utils.NoSuchArgumentError:
mode_arg = None
_encoding = None
try:
_encoding = utils.get_argument_from_call(node, position=2)
except utils.NoSuchArgumentError:
try:
_encoding = utils.get_argument_from_call(node,
keyword='encoding')
except utils.NoSuchArgumentError:
pass
if _encoding is None:
if mode_arg is not None:
mode = utils.safe_infer(mode_arg)
if (mode_arg is not None and isinstance(mode, astroid.Const) and
'b' in getattr(mode, 'value', '')):
# Files opened as binary don't need an encoding.
return
else:
self.add_message('open-without-encoding', node=node)
示例12: visit_asyncwith
def visit_asyncwith(self, node):
for ctx_mgr, _ in node.items:
infered = checker_utils.safe_infer(ctx_mgr)
if infered is None or infered is astroid.YES:
continue
if isinstance(infered, astroid.Instance):
try:
infered.getattr('__aenter__')
infered.getattr('__aexit__')
except exceptions.NotFoundError:
if isinstance(infered, astroid.Instance):
# If we do not know the bases of this class,
# just skip it.
if not checker_utils.has_known_bases(infered):
continue
# Just ignore mixin classes.
if self._ignore_mixin_members:
if infered.name[-5:].lower() == 'mixin':
continue
else:
continue
self.add_message('not-async-context-manager',
node=node, args=(infered.name, ))
示例13: visit_call
def visit_call(self, node):
"""Visit a Call node."""
if hasattr(node, 'func'):
infer = utils.safe_infer(node.func)
if infer:
if getattr(node.func, 'name', None) == 'set_trace':
self.add_message('set-trace', node=node)
示例14: visit_subscript
def visit_subscript(self, node):
supported_protocol = None
if isinstance(node.value, (astroid.ListComp, astroid.DictComp)):
return
if node.ctx == astroid.Load:
supported_protocol = supports_getitem
msg = "unsubscriptable-object"
elif node.ctx == astroid.Store:
supported_protocol = supports_setitem
msg = "unsupported-assignment-operation"
elif node.ctx == astroid.Del:
supported_protocol = supports_delitem
msg = "unsupported-delete-operation"
if isinstance(node.value, astroid.SetComp):
self.add_message(msg, args=node.value.as_string(), node=node.value)
return
if is_inside_abstract_class(node):
return
inferred = safe_infer(node.value)
if inferred is None or inferred is astroid.YES:
return
if not supported_protocol(inferred):
self.add_message(msg, args=node.value.as_string(), node=node.value)
示例15: _no_context_variadic
def _no_context_variadic(node, variadic_name, variadic_type, variadics):
"""Verify if the given call node has variadic nodes without context
This is a workaround for handling cases of nested call functions
which don't have the specific call context at hand.
Variadic arguments (variable positional arguments and variable
keyword arguments) are inferred, inherently wrong, by astroid
as a Tuple, respectively a Dict with empty elements.
This can lead pylint to believe that a function call receives
too few arguments.
"""
statement = node.statement()
for name in statement.nodes_of_class(astroid.Name):
if name.name != variadic_name:
continue
inferred = safe_infer(name)
if isinstance(inferred, (astroid.List, astroid.Tuple)):
length = len(inferred.elts)
elif isinstance(inferred, astroid.Dict):
length = len(inferred.items)
else:
continue
inferred_statement = inferred.statement()
if not length and isinstance(inferred_statement, astroid.FunctionDef):
is_in_starred_context = _has_parent_of_type(node, variadic_type, statement)
used_as_starred_argument = _is_name_used_as_variadic(name, variadics)
if is_in_starred_context or used_as_starred_argument:
return True
return False