fname
stringlengths
63
176
rel_fname
stringclasses
706 values
line
int64
-1
4.5k
name
stringlengths
1
81
kind
stringclasses
2 values
category
stringclasses
2 values
info
stringlengths
0
77.9k
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,261
add_message
ref
function
self.add_message("unnecessary-pass", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,264
_is_one_arg_pos_call
def
function
def _is_one_arg_pos_call(call): """Is this a call with exactly 1 argument, where that argument is positional? """ return isinstance(call, nodes.Call) and len(call.args) == 1 and not call.keywords
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,271
_infer_dunder_doc_attribute
def
function
def _infer_dunder_doc_attribute(node): # Try to see if we have a `__doc__` attribute. try: docstring = node["__doc__"] except KeyError: return None docstring = utils.safe_infer(docstring) if not docstring: return None if not isinstance(docstring, nodes.Const): return None return docstring.value
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,278
safe_infer
ref
function
docstring = utils.safe_infer(docstring)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,286
ComparisonChecker
def
class
_check_singleton_comparison _check_nan_comparison _check_literal_comparison _check_logical_tautology _check_callable_comparison visit_compare _check_unidiomatic_typecheck _check_type_x_is_y
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,338
_check_singleton_comparison
def
function
def _check_singleton_comparison( self, left_value, right_value, root_node, checking_for_absence: bool = _False ): """Check if == or != is being used to compare a singleton value.""" singleton_values = (_True, _False, None) def _is_singleton_const(node) -> bool: return isinstance(node, nodes.Const) and any( node.value is value for value in singleton_values ) if _is_singleton_const(left_value): singleton, other_value = left_value.value, right_value elif _is_singleton_const(right_value): singleton, other_value = right_value.value, left_value else: return singleton_comparison_example = {_False: "'{} is {}'", _True: "'{} is not {}'"} # _True/_False singletons have a special-cased message in case the user is # mistakenly using == or != to check for truthiness if singleton in {_True, _False}: suggestion_template = ( "{} if checking for the singleton value {}, or {} if testing for {}" ) truthiness_example = {_False: "not {}", _True: "{}"} truthiness_phrase = {_True: "truthiness", _False: "falsiness"} # Looks for comparisons like x == _True or x != _False checking_truthiness = singleton is not checking_for_absence suggestion = suggestion_template.format( singleton_comparison_example[checking_for_absence].format( left_value.as_string(), right_value.as_string() ), singleton, ( "'bool({})'" if not utils.is_test_condition(root_node) and checking_truthiness else "'{}'" ).format( truthiness_example[checking_truthiness].format( other_value.as_string() ) ), truthiness_phrase[checking_truthiness], ) else: suggestion = singleton_comparison_example[checking_for_absence].format( left_value.as_string(), right_value.as_string() ) self.add_message( "singleton-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_nan_comparison( self, left_value, right_value, root_node, checking_for_absence: bool = _False ): def _is_float_nan(node): try: if isinstance(node, nodes.Call) and len(node.args) == 1: if ( node.args[0].value.lower() == "nan" and node.inferred()[0].pytype() == "builtins.float" ): return _True return _False except AttributeError: return _False def _is_numpy_nan(node): if isinstance(node, nodes.Attribute) and node.attrname == "NaN": if isinstance(node.expr, nodes.Name): return node.expr.name in {"numpy", "nmp", "np"} return _False def _is_nan(node) -> bool: return _is_float_nan(node) or _is_numpy_nan(node) nan_left = _is_nan(left_value) if not nan_left and not _is_nan(right_value): return absence_text = "" if checking_for_absence: absence_text = "not " if nan_left: suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'" else: suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'" self.add_message( "nan-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,344
_is_singleton_const
def
function
def _is_singleton_const(node) -> bool: return isinstance(node, nodes.Const) and any( node.value is value for value in singleton_values ) if _is_singleton_const(left_value): singleton, other_value = left_value.value, right_value elif _is_singleton_const(right_value): singleton, other_value = right_value.value, left_value else: return singleton_comparison_example = {_False: "'{} is {}'", _True: "'{} is not {}'"} # _True/_False singletons have a special-cased message in case the user is # mistakenly using == or != to check for truthiness if singleton in {_True, _False}: suggestion_template = ( "{} if checking for the singleton value {}, or {} if testing for {}" ) truthiness_example = {_False: "not {}", _True: "{}"} truthiness_phrase = {_True: "truthiness", _False: "falsiness"} # Looks for comparisons like x == _True or x != _False checking_truthiness = singleton is not checking_for_absence suggestion = suggestion_template.format( singleton_comparison_example[checking_for_absence].format( left_value.as_string(), right_value.as_string() ), singleton, ( "'bool({})'" if not utils.is_test_condition(root_node) and checking_truthiness else "'{}'" ).format( truthiness_example[checking_truthiness].format( other_value.as_string() ) ), truthiness_phrase[checking_truthiness], ) else: suggestion = singleton_comparison_example[checking_for_absence].format( left_value.as_string(), right_value.as_string() ) self.add_message( "singleton-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_nan_comparison( self, left_value, right_value, root_node, checking_for_absence: bool = _False ): def _is_float_nan(node): try: if isinstance(node, nodes.Call) and len(node.args) == 1: if ( node.args[0].value.lower() == "nan" and node.inferred()[0].pytype() == "builtins.float" ): return _True return _False except AttributeError: return _False def _is_numpy_nan(node): if isinstance(node, nodes.Attribute) and node.attrname == "NaN": if isinstance(node.expr, nodes.Name): return node.expr.name in {"numpy", "nmp", "np"} return _False def _is_nan(node) -> bool: return _is_float_nan(node) or _is_numpy_nan(node) nan_left = _is_nan(left_value) if not nan_left and not _is_nan(right_value): return absence_text = "" if checking_for_absence: absence_text = "not " if nan_left: suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'" else: suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'" self.add_message( "nan-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,349
_is_singleton_const
ref
function
if _is_singleton_const(left_value):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,351
_is_singleton_const
ref
function
elif _is_singleton_const(right_value):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,372
as_string
ref
function
left_value.as_string(), right_value.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,372
as_string
ref
function
left_value.as_string(), right_value.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,377
is_test_condition
ref
function
if not utils.is_test_condition(root_node) and checking_truthiness
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,381
as_string
ref
function
other_value.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,388
as_string
ref
function
left_value.as_string(), right_value.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,388
as_string
ref
function
left_value.as_string(), right_value.as_string()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,390
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,393
as_string
ref
function
args=(f"'{root_node.as_string()}'", suggestion),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,396
_check_nan_comparison
def
function
def _check_nan_comparison( self, left_value, right_value, root_node, checking_for_absence: bool = _False ): def _is_float_nan(node): try: if isinstance(node, nodes.Call) and len(node.args) == 1: if ( node.args[0].value.lower() == "nan" and node.inferred()[0].pytype() == "builtins.float" ): return _True return _False except AttributeError: return _False def _is_numpy_nan(node): if isinstance(node, nodes.Attribute) and node.attrname == "NaN": if isinstance(node.expr, nodes.Name): return node.expr.name in {"numpy", "nmp", "np"} return _False def _is_nan(node) -> bool: return _is_float_nan(node) or _is_numpy_nan(node) nan_left = _is_nan(left_value) if not nan_left and not _is_nan(right_value): return absence_text = "" if checking_for_absence: absence_text = "not " if nan_left: suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'" else: suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'" self.add_message( "nan-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,399
_is_float_nan
def
function
def _is_float_nan(node): try: if isinstance(node, nodes.Call) and len(node.args) == 1: if ( node.args[0].value.lower() == "nan" and node.inferred()[0].pytype() == "builtins.float" ): return _True return _False except AttributeError: return _False def _is_numpy_nan(node): if isinstance(node, nodes.Attribute) and node.attrname == "NaN": if isinstance(node.expr, nodes.Name): return node.expr.name in {"numpy", "nmp", "np"} return _False def _is_nan(node) -> bool: return _is_float_nan(node) or _is_numpy_nan(node) nan_left = _is_nan(left_value) if not nan_left and not _is_nan(right_value): return absence_text = "" if checking_for_absence: absence_text = "not " if nan_left: suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'" else: suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'" self.add_message( "nan-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,404
inferred
ref
function
and node.inferred()[0].pytype() == "builtins.float"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,404
pytype
ref
function
and node.inferred()[0].pytype() == "builtins.float"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,411
_is_numpy_nan
def
function
def _is_numpy_nan(node): if isinstance(node, nodes.Attribute) and node.attrname == "NaN": if isinstance(node.expr, nodes.Name): return node.expr.name in {"numpy", "nmp", "np"} return _False def _is_nan(node) -> bool: return _is_float_nan(node) or _is_numpy_nan(node) nan_left = _is_nan(left_value) if not nan_left and not _is_nan(right_value): return absence_text = "" if checking_for_absence: absence_text = "not " if nan_left: suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'" else: suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'" self.add_message( "nan-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,417
_is_nan
def
function
def _is_nan(node) -> bool: return _is_float_nan(node) or _is_numpy_nan(node) nan_left = _is_nan(left_value) if not nan_left and not _is_nan(right_value): return absence_text = "" if checking_for_absence: absence_text = "not " if nan_left: suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'" else: suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'" self.add_message( "nan-comparison", node=root_node, args=(f"'{root_node.as_string()}'", suggestion), ) def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,418
_is_float_nan
ref
function
return _is_float_nan(node) or _is_numpy_nan(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,418
_is_numpy_nan
ref
function
return _is_float_nan(node) or _is_numpy_nan(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,420
_is_nan
ref
function
nan_left = _is_nan(left_value)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,421
_is_nan
ref
function
if not nan_left and not _is_nan(right_value):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,428
as_string
ref
function
suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,430
as_string
ref
function
suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,431
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,434
as_string
ref
function
args=(f"'{root_node.as_string()}'", suggestion),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,437
_check_literal_comparison
def
function
def _check_literal_comparison(self, literal, node: nodes.Compare): """Check if we compare to a literal, which is usually what we do not want to do.""" is_other_literal = isinstance(literal, (nodes.List, nodes.Dict, nodes.Set)) is_const = _False if isinstance(literal, nodes.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in these values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node) def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,448
add_message
ref
function
self.add_message("literal-comparison", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,450
_check_logical_tautology
def
function
def _check_logical_tautology(self, node: nodes.Compare): """Check if identifier is compared against itself. :param node: Compare node :Example: val = 786 if val == val: # [comparison-with-itself] pass """ left_operand = node.left right_operand = node.ops[0][1] operator = node.ops[0][0] if isinstance(left_operand, nodes.Const) and isinstance( right_operand, nodes.Const ): left_operand = left_operand.value right_operand = right_operand.value elif isinstance(left_operand, nodes.Name) and isinstance( right_operand, nodes.Name ): left_operand = left_operand.name right_operand = right_operand.name if left_operand == right_operand: suggestion = f"{left_operand} {operator} {right_operand}" self.add_message("comparison-with-itself", node=node, args=(suggestion,)) def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,474
add_message
ref
function
self.add_message("comparison-with-itself", node=node, args=(suggestion,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,476
_check_callable_comparison
def
function
def _check_callable_comparison(self, node): operator = node.ops[0][0] if operator not in COMPARISON_OPERATORS: return bare_callables = (nodes.FunctionDef, astroid.BoundMethod) left_operand, right_operand = node.left, node.ops[0][1] # this message should be emitted only when there is comparison of bare callable # with non bare callable. number_of_bare_callables = 0 for operand in left_operand, right_operand: inferred = utils.safe_infer(operand) # Ignore callables that raise, as well as typing constants # implemented as functions (that raise via their decorator) if ( isinstance(inferred, bare_callables) and "typing._SpecialForm" not in inferred.decoratornames() and not any(isinstance(x, nodes.Raise) for x in inferred.body) ): number_of_bare_callables += 1 if number_of_bare_callables == 1: self.add_message("comparison-with-callable", node=node) @utils.check_messages( "singleton-comparison", "unidiomatic-typecheck", "literal-comparison", "comparison-with-itself", "comparison-with-callable", ) def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,487
safe_infer
ref
function
inferred = utils.safe_infer(operand)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,492
decoratornames
ref
function
and "typing._SpecialForm" not in inferred.decoratornames()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,497
add_message
ref
function
self.add_message("comparison-with-callable", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,499
check_messages
ref
function
@utils.check_messages(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,506
visit_compare
def
function
def visit_compare(self, node: nodes.Compare) -> None: self._check_callable_comparison(node) self._check_logical_tautology(node) self._check_unidiomatic_typecheck(node) # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in {"==", "!="}: self._check_singleton_comparison( left, right, node, checking_for_absence=operator == "!=" ) if operator in {"==", "!=", "is", "is not"}: self._check_nan_comparison( left, right, node, checking_for_absence=operator in {"!=", "is not"} ) if operator in {"is", "is not"}: self._check_literal_comparison(right, node) def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,507
_check_callable_comparison
ref
function
self._check_callable_comparison(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,508
_check_logical_tautology
ref
function
self._check_logical_tautology(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,509
_check_unidiomatic_typecheck
ref
function
self._check_unidiomatic_typecheck(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,519
_check_singleton_comparison
ref
function
self._check_singleton_comparison(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,524
_check_nan_comparison
ref
function
self._check_nan_comparison(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,528
_check_literal_comparison
ref
function
self._check_literal_comparison(right, node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,530
_check_unidiomatic_typecheck
def
function
def _check_unidiomatic_typecheck(self, node): operator, right = node.ops[0] if operator in TYPECHECK_COMPARISON_OPERATORS: left = node.left if _is_one_arg_pos_call(left): self._check_type_x_is_y(node, left, operator, right) def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,534
_is_one_arg_pos_call
ref
function
if _is_one_arg_pos_call(left):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,535
_check_type_x_is_y
ref
function
self._check_type_x_is_y(node, left, operator, right)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,537
_check_type_x_is_y
def
function
def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in {"is", "is not"} and _is_one_arg_pos_call(right): right_func = utils.safe_infer(right.func) if ( isinstance(right_func, nodes.ClassDef) and right_func.qname() == TYPE_QNAME ): # type(x) == type(a) right_arg = utils.safe_infer(right.args[0]) if not isinstance(right_arg, LITERAL_NODE_TYPES): # not e.g. type(x) == type([]) return self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,539
safe_infer
ref
function
left_func = utils.safe_infer(left.func)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,541
qname
ref
function
isinstance(left_func, nodes.ClassDef) and left_func.qname() == TYPE_QNAME
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,545
_is_one_arg_pos_call
ref
function
if operator in {"is", "is not"} and _is_one_arg_pos_call(right):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,546
safe_infer
ref
function
right_func = utils.safe_infer(right.func)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,549
qname
ref
function
and right_func.qname() == TYPE_QNAME
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,552
safe_infer
ref
function
right_arg = utils.safe_infer(right.args[0])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,556
add_message
ref
function
self.add_message("unidiomatic-typecheck", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,559
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(BasicErrorChecker(linter)) linter.register_checker(BasicChecker(linter)) linter.register_checker(NameChecker(linter)) linter.register_checker(DocStringChecker(linter)) linter.register_checker(PassChecker(linter)) linter.register_checker(ComparisonChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,560
register_checker
ref
function
linter.register_checker(BasicErrorChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,560
BasicErrorChecker
ref
function
linter.register_checker(BasicErrorChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,561
register_checker
ref
function
linter.register_checker(BasicChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,561
BasicChecker
ref
function
linter.register_checker(BasicChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,562
register_checker
ref
function
linter.register_checker(NameChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,562
NameChecker
ref
function
linter.register_checker(NameChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,563
register_checker
ref
function
linter.register_checker(DocStringChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,563
DocStringChecker
ref
function
linter.register_checker(DocStringChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,564
register_checker
ref
function
linter.register_checker(PassChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,564
PassChecker
ref
function
linter.register_checker(PassChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,565
register_checker
ref
function
linter.register_checker(ComparisonChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base.py
pylint/checkers/base.py
2,565
ComparisonChecker
ref
function
linter.register_checker(ComparisonChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
34
BaseChecker
def
class
__init__ __gt__ __repr__ __str__ get_full_documentation add_message check_consistency create_message_definition_from_tuple messages get_message_definition open close
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
72
get_full_documentation
ref
function
return self.get_full_documentation(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
73
options_and_values
ref
function
msgs=self.msgs, options=self.options_and_values(), reports=self.reports
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
76
get_full_documentation
def
function
def get_full_documentation(self, msgs, options, reports, doc=None, module=None): result = "" checker_title = f"{self.name.replace('_', ' ').title()} checker" if module: # Provide anchor to link against result += f".. _{module}:\n\n" result += f"{get_rst_title(checker_title, '~')}\n" if module: result += f"This checker is provided by ``{module}``.\n" result += f"Verbatim name of the checker is ``{self.name}``.\n\n" if doc: # Provide anchor to link against result += get_rst_title(f"{checker_title} Documentation", "^") result += f"{cleandoc(doc)}\n\n" # options might be an empty generator and not be _False when cast to boolean options = list(options) if options: result += get_rst_title(f"{checker_title} Options", "^") result += f"{get_rst_section(None, options)}\n" if msgs: result += get_rst_title(f"{checker_title} Messages", "^") for msgid, msg in sorted( msgs.items(), key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1]) ): msg = self.create_message_definition_from_tuple(msgid, msg) result += f"{msg.format_help(checkerref=_False)}\n" result += "\n" if reports: result += get_rst_title(f"{checker_title} Reports", "^") for report in reports: result += ( ":%s: %s\n" % report[:2] # pylint: disable=consider-using-f-string ) result += "\n" result += "\n" return result def add_message( self, msgid: str, line: Optional[int] = None, node: Optional[nodes.NodeNG] = None, args: Any = None, confidence: Optional[Confidence] = None, col_offset: Optional[int] = None, end_lineno: Optional[int] = None, end_col_offset: Optional[int] = None, ) -> None: self.linter.add_message( msgid, line, node, args, confidence, col_offset, end_lineno, end_col_offset ) def check_consistency(self): """Check the consistency of msgid. msg ids for a checker should be a string of len 4, where the two first characters are the checker id and the two last the msg id in this checker. :raises InvalidMessageError: If the checker id in the messages are not always the same. """ checker_id = None existing_ids = [] for message in self.messages: if checker_id is not None and checker_id != message.msgid[1:3]: error_msg = "Inconsistent checker part in message id " error_msg += f"'{message.msgid}' (expected 'x{checker_id}xx' " error_msg += f"because we already had {existing_ids})." raise InvalidMessageError(error_msg) checker_id = message.msgid[1:3] existing_ids.append(message.msgid) def create_message_definition_from_tuple(self, msgid, msg_tuple): if implements(self, (IRawChecker, ITokenChecker)): default_scope = WarningScope.LINE else: default_scope = WarningScope.NODE options = {} if len(msg_tuple) > 3: (msg, symbol, descr, options) = msg_tuple elif len(msg_tuple) > 2: (msg, symbol, descr) = msg_tuple else: error_msg = """Messages should have a msgid and a symbol. Something like this :
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
82
get_rst_title
ref
function
result += f"{get_rst_title(checker_title, '~')}\n"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
88
get_rst_title
ref
function
result += get_rst_title(f"{checker_title} Documentation", "^")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
93
get_rst_title
ref
function
result += get_rst_title(f"{checker_title} Options", "^")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
94
get_rst_section
ref
function
result += f"{get_rst_section(None, options)}\n"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
96
get_rst_title
ref
function
result += get_rst_title(f"{checker_title} Messages", "^")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
100
create_message_definition_from_tuple
ref
function
msg = self.create_message_definition_from_tuple(msgid, msg)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
101
format_help
ref
function
result += f"{msg.format_help(checkerref=False)}\n"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
104
get_rst_title
ref
function
result += get_rst_title(f"{checker_title} Reports", "^")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
113
add_message
def
function
def add_message( self, msgid: str, line: Optional[int] = None, node: Optional[nodes.NodeNG] = None, args: Any = None, confidence: Optional[Confidence] = None, col_offset: Optional[int] = None, end_lineno: Optional[int] = None, end_col_offset: Optional[int] = None, ) -> None: self.linter.add_message( msgid, line, node, args, confidence, col_offset, end_lineno, end_col_offset ) def check_consistency(self): """Check the consistency of msgid. msg ids for a checker should be a string of len 4, where the two first characters are the checker id and the two last the msg id in this checker. :raises InvalidMessageError: If the checker id in the messages are not always the same. """ checker_id = None existing_ids = [] for message in self.messages: if checker_id is not None and checker_id != message.msgid[1:3]: error_msg = "Inconsistent checker part in message id " error_msg += f"'{message.msgid}' (expected 'x{checker_id}xx' " error_msg += f"because we already had {existing_ids})." raise InvalidMessageError(error_msg) checker_id = message.msgid[1:3] existing_ids.append(message.msgid) def create_message_definition_from_tuple(self, msgid, msg_tuple): if implements(self, (IRawChecker, ITokenChecker)): default_scope = WarningScope.LINE else: default_scope = WarningScope.NODE options = {} if len(msg_tuple) > 3: (msg, symbol, descr, options) = msg_tuple elif len(msg_tuple) > 2: (msg, symbol, descr) = msg_tuple else: error_msg = """Messages should have a msgid and a symbol. Something like this :
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
124
add_message
ref
function
self.linter.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
128
check_consistency
def
function
def check_consistency(self): """Check the consistency of msgid. msg ids for a checker should be a string of len 4, where the two first characters are the checker id and the two last the msg id in this checker. :raises InvalidMessageError: If the checker id in the messages are not always the same. """ checker_id = None existing_ids = [] for message in self.messages: if checker_id is not None and checker_id != message.msgid[1:3]: error_msg = "Inconsistent checker part in message id " error_msg += f"'{message.msgid}' (expected 'x{checker_id}xx' " error_msg += f"because we already had {existing_ids})." raise InvalidMessageError(error_msg) checker_id = message.msgid[1:3] existing_ids.append(message.msgid) def create_message_definition_from_tuple(self, msgid, msg_tuple): if implements(self, (IRawChecker, ITokenChecker)): default_scope = WarningScope.LINE else: default_scope = WarningScope.NODE options = {} if len(msg_tuple) > 3: (msg, symbol, descr, options) = msg_tuple elif len(msg_tuple) > 2: (msg, symbol, descr) = msg_tuple else: error_msg = """Messages should have a msgid and a symbol. Something like this :
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
145
InvalidMessageError
ref
function
raise InvalidMessageError(error_msg)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
149
create_message_definition_from_tuple
def
function
def create_message_definition_from_tuple(self, msgid, msg_tuple): if implements(self, (IRawChecker, ITokenChecker)): default_scope = WarningScope.LINE else: default_scope = WarningScope.NODE options = {} if len(msg_tuple) > 3: (msg, symbol, descr, options) = msg_tuple elif len(msg_tuple) > 2: (msg, symbol, descr) = msg_tuple else: error_msg = """Messages should have a msgid and a symbol. Something like this :
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
150
implements
ref
function
if implements(self, (IRawChecker, ITokenChecker)):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
169
InvalidMessageError
ref
function
raise InvalidMessageError(error_msg)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
171
MessageDefinition
ref
function
return MessageDefinition(self, msgid, msg, descr, symbol, **options)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
174
messages
def
function
def messages(self) -> list: return [ self.create_message_definition_from_tuple(msgid, msg_tuple) for msgid, msg_tuple in sorted(self.msgs.items()) ] # dummy methods implementing the IChecker interface def get_message_definition(self, msgid): for message_definition in self.messages: if message_definition.msgid == msgid: return message_definition error_msg = f"MessageDefinition for '{msgid}' does not exists. " error_msg += f"Choose from {[m.msgid for m in self.messages]}." raise InvalidMessageError(error_msg) def open(self): """Called before visiting project (i.e. set of modules).""" def close(self): """Called after visiting project (i.e set of modules)."""
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
176
create_message_definition_from_tuple
ref
function
self.create_message_definition_from_tuple(msgid, msg_tuple)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
182
get_message_definition
def
function
def get_message_definition(self, msgid): for message_definition in self.messages: if message_definition.msgid == msgid: return message_definition error_msg = f"MessageDefinition for '{msgid}' does not exists. " error_msg += f"Choose from {[m.msgid for m in self.messages]}." raise InvalidMessageError(error_msg) def open(self): """Called before visiting project (i.e. set of modules).""" def close(self): """Called after visiting project (i.e set of modules)."""
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
188
InvalidMessageError
ref
function
raise InvalidMessageError(error_msg)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
193
close
def
function
def close(self): """Called after visiting project (i.e set of modules)."""
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
197
BaseTokenChecker
def
class
process_tokens
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/base_checker.py
pylint/checkers/base_checker.py
200
process_tokens
def
function
def process_tokens(self, tokens): """Should be overridden by subclasses.""" raise NotImplementedError()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/__init__.py
pylint/checkers/classes/__init__.py
12
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(ClassChecker(linter)) linter.register_checker(SpecialMethodsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/classes/__init__.py
pylint/checkers/classes/__init__.py
13
register_checker
ref
function
linter.register_checker(ClassChecker(linter))