本文整理汇总了Python中pylint.checkers.utils.has_known_bases函数的典型用法代码示例。如果您正苦于以下问题:Python has_known_bases函数的具体用法?Python has_known_bases怎么用?Python has_known_bases使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了has_known_bases函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _check_catching_non_exception
def _check_catching_non_exception(self, handler, exc, part):
if isinstance(exc, astroid.Tuple):
# Check if it is a tuple of exceptions.
inferred = [utils.safe_infer(elt) for elt in exc.elts]
if any(node is astroid.Uninferable for node in inferred):
# Don't emit if we don't know every component.
return
if all(
node
and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
for node in inferred
):
return
if not isinstance(exc, astroid.ClassDef):
# Don't emit the warning if the infered stmt
# is None, but the exception handler is something else,
# maybe it was redefined.
if isinstance(exc, astroid.Const) and exc.value is None:
if (
isinstance(handler.type, astroid.Const)
and handler.type.value is None
) or handler.type.parent_of(exc):
# If the exception handler catches None or
# the exception component, which is None, is
# defined by the entire exception handler, then
# emit a warning.
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
else:
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
return
if (
not utils.inherit_from_std_ex(exc)
and exc.name not in self._builtin_exceptions
):
if utils.has_known_bases(exc):
self.add_message(
"catching-non-exception", node=handler.type, args=(exc.name,)
)
示例2: visit_classdef
def visit_classdef(self, cls):
if (not utils.inherit_from_std_ex(cls) and
utils.has_known_bases(cls)):
if cls.newstyle:
self._checker.add_message('raising-non-exception', node=self._node)
else:
self._checker.add_message('nonstandard-exception', node=self._node)
示例3: 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, ))
示例4: 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,)
)
示例5: _check_binop_errors
def _check_binop_errors(self, node):
for error in node.type_errors():
# Let the error customize its output.
if any(isinstance(obj, astroid.ClassDef) and not has_known_bases(obj)
for obj in (error.left_type, error.right_type)):
continue
self.add_message('unsupported-binary-operation',
args=str(error), node=node)
示例6: visit_callfunc
def visit_callfunc(self, node):
"""check property usage"""
parent = node.parent.frame()
if isinstance(parent, astroid.Class) and not parent.newstyle and isinstance(node.func, astroid.Name):
confidence = INFERENCE if has_known_bases(parent) else INFERENCE_FAILURE
name = node.func.name
if name == "property":
self.add_message("property-on-old-class", node=node, confidence=confidence)
示例7: _check_raise_value
def _check_raise_value(self, node, expr):
"""check for bad values, string exception and class inheritance
"""
value_found = True
if isinstance(expr, astroid.Const):
value = expr.value
if not isinstance(value, str):
# raising-string will be emitted from python3 porting checker.
self.add_message('raising-bad-type', node=node,
args=value.__class__.__name__)
elif ((isinstance(expr, astroid.Name) and
expr.name in ('None', 'True', 'False')) or
isinstance(expr, (astroid.List, astroid.Dict, astroid.Tuple,
astroid.Module, astroid.FunctionDef))):
emit = True
if not PY3K and isinstance(expr, astroid.Tuple) and expr.elts:
# On Python 2, using the following is not an error:
# raise (ZeroDivisionError, None)
# raise (ZeroDivisionError, )
# What's left to do is to check that the first
# argument is indeed an exception.
# Verifying the other arguments is not
# the scope of this check.
first = expr.elts[0]
inferred = safe_infer(first)
if isinstance(inferred, astroid.Instance):
# pylint: disable=protected-access
inferred = inferred._proxied
if (inferred is astroid.YES or
isinstance(inferred, astroid.ClassDef)
and inherit_from_std_ex(inferred)):
emit = False
if emit:
self.add_message('raising-bad-type',
node=node,
args=expr.name)
elif ((isinstance(expr, astroid.Name) and expr.name == 'NotImplemented')
or (isinstance(expr, astroid.Call) and
isinstance(expr.func, astroid.Name) and
expr.func.name == 'NotImplemented')):
self.add_message('notimplemented-raised', node=node)
elif isinstance(expr, (astroid.Instance, astroid.ClassDef)):
if isinstance(expr, astroid.Instance):
# pylint: disable=protected-access
expr = expr._proxied
if (isinstance(expr, astroid.ClassDef) and
not inherit_from_std_ex(expr) and
has_known_bases(expr)):
if expr.newstyle:
self.add_message('raising-non-exception', node=node)
else:
self.add_message('nonstandard-exception', node=node)
else:
value_found = False
else:
value_found = False
return value_found
示例8: visit_functiondef
def visit_functiondef(self, node):
"""check use of super"""
# ignore actual functions or method within a new style class
if not node.is_method():
return
klass = node.parent.frame()
for stmt in node.nodes_of_class(astroid.Call):
if node_frame_class(stmt) != node_frame_class(node):
# Don't look down in other scopes.
continue
expr = stmt.func
if not isinstance(expr, astroid.Attribute):
continue
call = expr.expr
# skip the test if using super
if not (isinstance(call, astroid.Call) and
isinstance(call.func, astroid.Name) and
call.func.name == 'super'):
continue
confidence = (INFERENCE if has_known_bases(klass)
else INFERENCE_FAILURE)
if not klass.newstyle:
# super should not be used on an old style class
self.add_message('super-on-old-class', node=node,
confidence=confidence)
else:
# super first arg should be the class
if not call.args and sys.version_info[0] == 3:
# unless Python 3
continue
try:
supcls = (call.args and next(call.args[0].infer())
or None)
except astroid.InferenceError:
continue
if supcls is None:
self.add_message('missing-super-argument', node=call,
confidence=confidence)
continue
if klass is not supcls:
name = None
# if supcls is not YES, then supcls was infered
# and use its name. Otherwise, try to look
# for call.args[0].name
if supcls is not astroid.YES:
name = supcls.name
else:
if hasattr(call.args[0], 'name'):
name = call.args[0].name
if name is not None:
self.add_message('bad-super-call', node=call, args=(name, ),
confidence=confidence)
示例9: visit_classdef
def visit_classdef(self, node):
"""init visit variable _accessed
"""
self._accessed.append(defaultdict(list))
self._check_bases_classes(node)
# if not an exception or a metaclass
if node.type == 'class' and has_known_bases(node):
try:
node.local_attr('__init__')
except astroid.NotFoundError:
self.add_message('no-init', args=node, node=node)
self._check_slots(node)
self._check_proper_bases(node)
self._check_consistent_mro(node)
示例10: visit_class
def visit_class(self, node):
""" Check __slots__ in old style classes and old
style class definition.
"""
if "__slots__" in node and not node.newstyle:
confidence = INFERENCE if has_known_bases(node) else INFERENCE_FAILURE
self.add_message("slots-on-old-class", node=node, confidence=confidence)
# The node type could be class, exception, metaclass, or
# interface. Presumably, the non-class-type nodes would always
# have an explicit base class anyway.
if not node.bases and node.type == "class" and not node.metaclass():
# We use confidence HIGH here because this message should only ever
# be emitted for classes at the root of the inheritance hierarchyself.
self.add_message("old-style-class", node=node, confidence=HIGH)
示例11: visit_with
def visit_with(self, node):
for ctx_mgr, _ in node.items:
context = astroid.context.InferenceContext()
infered = safe_infer(ctx_mgr, context=context)
if infered is None or infered is astroid.YES:
continue
if isinstance(infered, bases.Generator):
# Check if we are dealing with a function decorated
# with contextlib.contextmanager.
if decorated_with(infered.parent,
self.config.contextmanager_decorators):
continue
# If the parent of the generator is not the context manager itself,
# that means that it could have been returned from another
# function which was the real context manager.
# The following approach is more of a hack rather than a real
# solution: walk all the inferred statements for the
# given *ctx_mgr* and if you find one function scope
# which is decorated, consider it to be the real
# manager and give up, otherwise emit not-context-manager.
# See the test file for not_context_manager for a couple
# of self explaining tests.
for path in six.moves.filter(None, _unflatten(context.path)):
scope = path.scope()
if not isinstance(scope, astroid.FunctionDef):
continue
if decorated_with(scope,
self.config.contextmanager_decorators):
break
else:
self.add_message('not-context-manager',
node=node, args=(infered.name, ))
else:
try:
infered.getattr('__enter__')
infered.getattr('__exit__')
except exceptions.NotFoundError:
if isinstance(infered, astroid.Instance):
# If we do not know the bases of this class,
# just skip it.
if not has_known_bases(infered):
continue
# Just ignore mixin classes.
if self.config.ignore_mixin_members:
if infered.name[-5:].lower() == 'mixin':
continue
self.add_message('not-context-manager',
node=node, args=(infered.name, ))
示例12: visit_functiondef
def visit_functiondef(self, node):
if self.config.no_docstring_rgx.match(node.name) is None:
ftype = node.is_method() and 'method' or 'function'
if isinstance(node.parent.frame(), astroid.ClassDef):
overridden = False
confidence = (INFERENCE if has_known_bases(node.parent.frame())
else INFERENCE_FAILURE)
# check if node is from a method overridden by its ancestor
for ancestor in node.parent.frame().ancestors():
if node.name in ancestor and \
isinstance(ancestor[node.name], astroid.FunctionDef):
overridden = True
break
self._check_docstring(ftype, node,
report_missing=not overridden,
confidence=confidence)
else:
self._check_docstring(ftype, node)
示例13: _check_raise_value
def _check_raise_value(self, node, expr):
"""check for bad values, string exception and class inheritance
"""
value_found = True
if isinstance(expr, astroid.Const):
value = expr.value
if isinstance(value, str):
# raising-string will be emitted from python3 porting checker.
pass
else:
self.add_message('raising-bad-type', node=node,
args=value.__class__.__name__)
elif (isinstance(expr, astroid.Name) and \
expr.name in ('None', 'True', 'False')) or \
isinstance(expr, (astroid.List, astroid.Dict, astroid.Tuple,
astroid.Module, astroid.Function)):
self.add_message('raising-bad-type', node=node, args=expr.name)
elif ((isinstance(expr, astroid.Name) and expr.name == 'NotImplemented')
or (isinstance(expr, astroid.CallFunc) and
isinstance(expr.func, astroid.Name) and
expr.func.name == 'NotImplemented')):
self.add_message('notimplemented-raised', node=node)
elif isinstance(expr, (Instance, astroid.Class)):
if isinstance(expr, Instance):
expr = expr._proxied
if (isinstance(expr, astroid.Class) and
not inherit_from_std_ex(expr) and
expr.root().name != BUILTINS_NAME):
if expr.newstyle:
self.add_message('raising-non-exception', node=node)
else:
self.add_message(
'nonstandard-exception', node=node,
confidence=INFERENCE if has_known_bases(expr) else INFERENCE_FAILURE)
else:
value_found = False
else:
value_found = False
return value_found
示例14: _emit_no_member
def _emit_no_member(node, owner, owner_name, ignored_mixins):
"""Try to see if no-member should be emitted for the given owner.
The following cases are ignored:
* the owner is a function and it has decorators.
* the owner is an instance and it has __getattr__, __getattribute__ implemented
* the module is explicitly ignored from no-member checks
* the owner is a class and the name can be found in its metaclass.
* The access node is protected by an except handler, which handles
AttributeError, Exception or bare except.
"""
if node_ignores_exception(node, AttributeError):
return False
# skip None anyway
if isinstance(owner, astroid.Const) and owner.value is None:
return False
if is_super(owner) or getattr(owner, "type", None) == "metaclass":
return False
if ignored_mixins and owner_name[-5:].lower() == "mixin":
return False
if isinstance(owner, astroid.FunctionDef) and owner.decorators:
return False
if isinstance(owner, astroid.Instance):
if owner.has_dynamic_getattr() or not has_known_bases(owner):
return False
if isinstance(owner, objects.Super):
# Verify if we are dealing with an invalid Super object.
# If it is invalid, then there's no point in checking that
# it has the required attribute. Also, don't fail if the
# MRO is invalid.
try:
owner.super_mro()
except (exceptions.MroError, exceptions.SuperError):
return False
if not all(map(has_known_bases, owner.type.mro())):
return False
return True
示例15: leave_function
def leave_function(self, node):
"""leave function: check function's locals are consumed"""
not_consumed = self._to_consume.pop()[0]
if not (self.linter.is_message_enabled('unused-variable') or
self.linter.is_message_enabled('unused-argument')):
return
# don't check arguments of function which are only raising an exception
if is_error(node):
return
# don't check arguments of abstract methods or within an interface
is_method = node.is_method()
klass = node.parent.frame()
if is_method and (klass.type == 'interface' or node.is_abstract()):
return
if is_method and isinstance(klass, astroid.Class):
confidence = INFERENCE if has_known_bases(klass) else INFERENCE_FAILURE
else:
confidence = HIGH
authorized_rgx = self.config.dummy_variables_rgx
called_overridden = False
argnames = node.argnames()
global_names = set()
nonlocal_names = set()
for global_stmt in node.nodes_of_class(astroid.Global):
global_names.update(set(global_stmt.names))
for nonlocal_stmt in node.nodes_of_class(astroid.Nonlocal):
nonlocal_names.update(set(nonlocal_stmt.names))
for name, stmts in six.iteritems(not_consumed):
# ignore some special names specified by user configuration
if authorized_rgx.match(name):
continue
# ignore names imported by the global statement
# FIXME: should only ignore them if it's assigned latter
stmt = stmts[0]
if isinstance(stmt, astroid.Global):
continue
if isinstance(stmt, (astroid.Import, astroid.From)):
# Detect imports, assigned to global statements.
if global_names:
skip = False
for import_name, import_alias in stmt.names:
# If the import uses an alias, check only that.
# Otherwise, check only the import name.
if import_alias:
if import_alias in global_names:
skip = True
break
elif import_name in global_names:
skip = True
break
if skip:
continue
# care about functions with unknown argument (builtins)
if name in argnames:
if is_method:
# don't warn for the first argument of a (non static) method
if node.type != 'staticmethod' and name == argnames[0]:
continue
# don't warn for argument of an overridden method
if not called_overridden:
overridden = overridden_method(klass, node.name)
called_overridden = True
if overridden is not None and name in overridden.argnames():
continue
if node.name in PYMETHODS and node.name not in ('__init__', '__new__'):
continue
# don't check callback arguments
if any(node.name.startswith(cb) or node.name.endswith(cb)
for cb in self.config.callbacks):
continue
self.add_message('unused-argument', args=name, node=stmt,
confidence=confidence)
else:
if stmt.parent and isinstance(stmt.parent, astroid.Assign):
if name in nonlocal_names:
continue
self.add_message('unused-variable', args=name, node=stmt)