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/similar.py
pylint/checkers/similar.py
560
stripped_lines
def
function
def stripped_lines( lines: Iterable[str], ignore_comments: bool, ignore_docstrings: bool, ignore_imports: bool, ignore_signatures: bool,
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
577
parse
ref
function
tree = astroid.parse("".join(lines))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
592
_get_functions
def
function
def _get_functions( functions: List[nodes.NodeNG], tree: nodes.NodeNG ) -> List[nodes.NodeNG]: """Recursively get all functions including nested in the classes from the tree.""" for node in tree.body: if isinstance(node, (nodes.FunctionDef, nodes.AsyncFunctionDef)): functions.append(node) if isinstance( node, (nodes.ClassDef, nodes.FunctionDef, nodes.AsyncFunctionDef), ): _get_functions(functions, node) return functions functions = _get_functions([], tree) signature_lines = set( chain( *( range( func.lineno, func.body[0].lineno if func.body else func.tolineno + 1, ) for func in functions ) ) ) strippedlines = [] docstring = None for lineno, line in enumerate(lines, start=1): line = line.strip() if ignore_docstrings: if not docstring: if line.startswith('"""') or line.startswith("'''"): docstring = line[:3] line = line[3:] elif line.startswith('r"""') or line.startswith("r'''"): docstring = line[1:4] line = line[4:] if docstring: if line.endswith(docstring): docstring = None line = "" if ignore_imports: current_line_is_import = line_begins_import.get( lineno, current_line_is_import ) if current_line_is_import: line = "" if ignore_comments: line = line.split("#", 1)[0].strip() if ignore_signatures and lineno in signature_lines: line = "" if line: strippedlines.append( LineSpecifs(text=line, line_number=LineNumber(lineno - 1)) ) return strippedlines
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
605
_get_functions
ref
function
_get_functions(functions, node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
609
_get_functions
ref
function
functions = _get_functions([], tree)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
650
LineSpecifs
ref
function
LineSpecifs(text=line, line_number=LineNumber(lineno - 1))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
650
LineNumber
ref
function
LineSpecifs(text=line, line_number=LineNumber(lineno - 1))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
656
LineSet
def
class
__init__ __str__ __len__ __getitem__ __lt__ __hash__ __eq__ stripped_lines real_lines
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
673
stripped_lines
ref
function
self._stripped_lines = stripped_lines(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
698
stripped_lines
def
function
def stripped_lines(self): return self._stripped_lines @property def real_lines(self): return self._real_lines
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
702
real_lines
def
function
def real_lines(self): return self._real_lines
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
717
report_similarities
def
function
def report_similarities( sect, stats: LinterStats, old_stats: Optional[LinterStats],
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
724
table_lines_from_stats
ref
function
lines += table_lines_from_stats(stats, old_stats, "duplicated_lines")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
725
Table
ref
function
sect.append(Table(children=lines, cols=4, rheaders=1, cheaders=1))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
729
SimilarChecker
def
class
__init__ set_option open process_module close get_map_data reduce_map_data
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
803
set_option
def
function
def set_option(self, optname, value, action=None, optdict=None): """Method called to set an option (registered in the options list). Overridden to report options setting to Similar """ BaseChecker.set_option(self, optname, value, action, optdict) if optname == "min-similarity-lines": self.min_lines = self.config.min_similarity_lines elif optname == "ignore-comments": self.ignore_comments = self.config.ignore_comments elif optname == "ignore-docstrings": self.ignore_docstrings = self.config.ignore_docstrings elif optname == "ignore-imports": self.ignore_imports = self.config.ignore_imports elif optname == "ignore-signatures": self.ignore_signatures = self.config.ignore_signatures def open(self): """Init the checkers: reset linesets and statistics information.""" self.linesets = [] self.linter.stats.reset_duplicated_lines() def process_module(self, node: nodes.Module) -> None: """Process a module. the module's content is accessible via the stream object stream must implement the readlines method """ if self.linter.current_name is None: warnings.warn( ( "In pylint 3.0 the current_name attribute of the linter object should be a string. " "If unknown it should be initialized as an empty string." ), DeprecationWarning, ) with node.stream() as stream: self.append_stream(self.linter.current_name, stream, node.file_encoding) # type: ignore[arg-type] def close(self): """Compute and display similarities on closing (i.e. end of parsing).""" total = sum(len(lineset) for lineset in self.linesets) duplicated = 0 stats = self.linter.stats for num, couples in self._compute_sims(): msg = [] lineset = start_line = end_line = None for lineset, start_line, end_line in couples: msg.append(f"=={lineset.name}:[{start_line}:{end_line}]") msg.sort() if lineset: for line in lineset.real_lines[start_line:end_line]: msg.append(line.rstrip()) self.add_message("R0801", args=(len(couples), "\n".join(msg))) duplicated += num * (len(couples) - 1) stats.nb_duplicated_lines += int(duplicated) stats.percent_duplicated_lines += float(total and duplicated * 100.0 / total) def get_map_data(self): """Passthru override.""" return Similar.get_map_data(self) def reduce_map_data(self, linter, data): """Reduces and recombines data into a format that we can report on. The partner function of get_map_data() """ recombined = SimilarChecker(linter) recombined.min_lines = self.min_lines recombined.ignore_comments = self.ignore_comments recombined.ignore_docstrings = self.ignore_docstrings recombined.ignore_imports = self.ignore_imports recombined.ignore_signatures = self.ignore_signatures recombined.open() Similar.combine_mapreduce_data(recombined, linesets_collection=data) recombined.close()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
808
set_option
ref
function
BaseChecker.set_option(self, optname, value, action, optdict)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
823
reset_duplicated_lines
ref
function
self.linter.stats.reset_duplicated_lines()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
825
process_module
def
function
def process_module(self, node: nodes.Module) -> None: """Process a module. the module's content is accessible via the stream object stream must implement the readlines method """ if self.linter.current_name is None: warnings.warn( ( "In pylint 3.0 the current_name attribute of the linter object should be a string. " "If unknown it should be initialized as an empty string." ), DeprecationWarning, ) with node.stream() as stream: self.append_stream(self.linter.current_name, stream, node.file_encoding) # type: ignore[arg-type] def close(self): """Compute and display similarities on closing (i.e. end of parsing).""" total = sum(len(lineset) for lineset in self.linesets) duplicated = 0 stats = self.linter.stats for num, couples in self._compute_sims(): msg = [] lineset = start_line = end_line = None for lineset, start_line, end_line in couples: msg.append(f"=={lineset.name}:[{start_line}:{end_line}]") msg.sort() if lineset: for line in lineset.real_lines[start_line:end_line]: msg.append(line.rstrip()) self.add_message("R0801", args=(len(couples), "\n".join(msg))) duplicated += num * (len(couples) - 1) stats.nb_duplicated_lines += int(duplicated) stats.percent_duplicated_lines += float(total and duplicated * 100.0 / total) def get_map_data(self): """Passthru override.""" return Similar.get_map_data(self) def reduce_map_data(self, linter, data): """Reduces and recombines data into a format that we can report on. The partner function of get_map_data() """ recombined = SimilarChecker(linter) recombined.min_lines = self.min_lines recombined.ignore_comments = self.ignore_comments recombined.ignore_docstrings = self.ignore_docstrings recombined.ignore_imports = self.ignore_imports recombined.ignore_signatures = self.ignore_signatures recombined.open() Similar.combine_mapreduce_data(recombined, linesets_collection=data) recombined.close()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
840
stream
ref
function
with node.stream() as stream:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
841
append_stream
ref
function
self.append_stream(self.linter.current_name, stream, node.file_encoding) # type: ignore[arg-type]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
848
_compute_sims
ref
function
for num, couples in self._compute_sims():
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
859
add_message
ref
function
self.add_message("R0801", args=(len(couples), "\n".join(msg)))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
864
get_map_data
def
function
def get_map_data(self): """Returns the data we can use for a map/reduce process. In this case we are returning this instance's Linesets, that is all file information that will later be used for vectorisation. """ return self.linesets def combine_mapreduce_data(self, linesets_collection): """Reduces and recombines data into a format that we can report on. The partner function of get_map_data() """ self.linesets = [line for lineset in linesets_collection for line in lineset]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
866
get_map_data
ref
function
return Similar.get_map_data(self)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
868
reduce_map_data
def
function
def reduce_map_data(self, linter, data): """Reduces and recombines data into a format that we can report on. The partner function of get_map_data() """ recombined = SimilarChecker(linter) recombined.min_lines = self.min_lines recombined.ignore_comments = self.ignore_comments recombined.ignore_docstrings = self.ignore_docstrings recombined.ignore_imports = self.ignore_imports recombined.ignore_signatures = self.ignore_signatures recombined.open() Similar.combine_mapreduce_data(recombined, linesets_collection=data) recombined.close()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
873
SimilarChecker
ref
function
recombined = SimilarChecker(linter)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
880
combine_mapreduce_data
ref
function
Similar.combine_mapreduce_data(recombined, linesets_collection=data)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
884
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(SimilarChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
885
register_checker
ref
function
linter.register_checker(SimilarChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
885
SimilarChecker
ref
function
linter.register_checker(SimilarChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
888
usage
def
function
def usage(status=0): """Display command line usage information.""" print("finds copy pasted blocks in a set of files") print() print( "Usage: symilar [-d|--duplicates min_duplicated_lines] \
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
899
Run
def
function
def Run(argv=None): """Standalone command line access point.""" if argv is None: argv = sys.argv[1:] s_opts = "hdi" l_opts = ( "help", "duplicates=", "ignore-comments", "ignore-imports", "ignore-docstrings", "ignore-signatures", ) min_lines = DEFAULT_MIN_SIMILARITY_LINE ignore_comments = _False ignore_docstrings = _False ignore_imports = _False ignore_signatures = _False opts, args = getopt(argv, s_opts, l_opts) for opt, val in opts: if opt in {"-d", "--duplicates"}: min_lines = int(val) elif opt in {"-h", "--help"}: usage() elif opt in {"-i", "--ignore-comments"}: ignore_comments = _True elif opt in {"--ignore-docstrings"}: ignore_docstrings = _True elif opt in {"--ignore-imports"}: ignore_imports = _True elif opt in {"--ignore-signatures"}: ignore_signatures = _True if not args: usage(1) sim = Similar( min_lines, ignore_comments, ignore_docstrings, ignore_imports, ignore_signatures ) for filename in args: with open(filename, encoding="utf-8") as stream: sim.append_stream(filename, stream) sim.run() sys.exit(0)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
923
usage
ref
function
usage()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
933
usage
ref
function
usage(1)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
934
Similar
ref
function
sim = Similar(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
939
append_stream
ref
function
sim.append_stream(filename, stream)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
940
run
ref
function
sim.run()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/similar.py
pylint/checkers/similar.py
945
Run
ref
function
Run()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
58
EmailFilter
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
61
URLFilter
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
64
WikiWordFilter
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
67
Filter
def
class
_skip
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
68
_skip
def
function
def _skip(self, word): raise NotImplementedError class Chunker: # type: ignore[no-redef] pass def get_tokenizer( tag=None, chunkers=None, filters=None ): # pylint: disable=unused-argument return Filter()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
71
Chunker
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
74
get_tokenizer
def
function
def get_tokenizer( tag=None, chunkers=None, filters=None ): # pylint: disable=unused-argument return Filter()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
77
Filter
ref
function
return Filter()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
81
Broker
ref
function
br = enchant.Broker()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
82
list_dicts
ref
function
dicts = br.list_dicts()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
93
WordsWithDigitsFilter
def
class
_skip
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
96
_skip
def
function
def _skip(self, word): raise NotImplementedError class Chunker: # type: ignore[no-redef] pass def get_tokenizer( tag=None, chunkers=None, filters=None ): # pylint: disable=unused-argument return Filter()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
100
WordsWithUnderscores
def
class
_skip
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
106
_skip
def
function
def _skip(self, word): raise NotImplementedError class Chunker: # type: ignore[no-redef] pass def get_tokenizer( tag=None, chunkers=None, filters=None ): # pylint: disable=unused-argument return Filter()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
110
RegExFilter
def
class
_skip
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
120
_skip
def
function
def _skip(self, word) -> bool: return bool(self._pattern.match(word))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
124
CamelCasedWord
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
135
SphinxDirectives
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
147
ForwardSlashChunker
def
class
next _next
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
173
_next
def
function
def _next(self): while _True: if "/" not in self._text: return (self._text, 0) pre_text, post_text = self._text.split("/", 1) if not pre_text or not post_text: break if not pre_text[-1].isalpha() or not post_text[0].isalpha(): raise StopIteration() self._text = pre_text + " " + post_text raise StopIteration()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
189
_strip_code_flanked_in_backticks
def
function
def _strip_code_flanked_in_backticks(line: str) -> str: """Alter line so code flanked in backticks is ignored. Pyenchant automatically strips backticks when parsing tokens, so this cannot be done at the individual filter level. """ def replace_code_but_leave_surrounding_characters(match_obj) -> str: return match_obj.group(1) + match_obj.group(5) return CODE_FLANKED_IN_BACKTICK_REGEX.sub( replace_code_but_leave_surrounding_characters, line )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
196
replace_code_but_leave_surrounding_characters
def
function
def replace_code_but_leave_surrounding_characters(match_obj) -> str: return match_obj.group(1) + match_obj.group(5) return CODE_FLANKED_IN_BACKTICK_REGEX.sub( replace_code_but_leave_surrounding_characters, line )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
204
SpellingChecker
def
class
open close _check_spelling process_tokens visit_module visit_classdef visit_functiondef _check_docstring
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
314
expanduser
ref
function
self.config.spelling_private_dict_file = os.path.expanduser(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
319
DictWithPWL
ref
function
self.spelling_dict = enchant.DictWithPWL(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
326
Dict
ref
function
self.spelling_dict = enchant.Dict(dict_name)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
331
get_tokenizer
ref
function
self.tokenizer = get_tokenizer(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
350
_check_spelling
def
function
def _check_spelling(self, msgid, line, line_num): original_line = line try: initial_space = re.search(r"^[^\S]\s*", line).regs[0][1] except (IndexError, AttributeError): initial_space = 0 if line.strip().startswith("#") and "docstring" not in msgid: line = line.strip()[1:] # A ``Filter`` cannot determine if the directive is at the beginning of a line, # nor determine if a colon is present or not (``pyenchant`` strips trailing colons). # So implementing this here. for iter_directive in self.ignore_comment_directive_list: if line.startswith(" " + iter_directive): line = line[(len(iter_directive) + 1) :] break starts_with_comment = _True else: starts_with_comment = _False line = _strip_code_flanked_in_backticks(line) for word, word_start_at in self.tokenizer(line.strip()): word_start_at += initial_space lower_cased_word = word.casefold() # Skip words from ignore list. if word in self.ignore_list or lower_cased_word in self.ignore_list: continue # Strip starting u' from unicode literals and r' from raw strings. if word.startswith(("u'", 'u"', "r'", 'r"')) and len(word) > 2: word = word[2:] lower_cased_word = lower_cased_word[2:] # If it is a known word, then continue. try: if self.spelling_dict.check(lower_cased_word): # The lower cased version of word passed spell checking continue # If we reached this far, it means there was a spelling mistake. # Let's retry with the original work because 'unicode' is a # spelling mistake but 'Unicode' is not if self.spelling_dict.check(word): continue except enchant.errors.Error: self.add_message( "invalid-characters-in-docstring", line=line_num, args=(word,) ) continue # Store word to private dict or raise a message. if self.config.spelling_store_unknown_words: if lower_cased_word not in self.unknown_words: self.private_dict_file.write(f"{lower_cased_word}\n") self.unknown_words.add(lower_cased_word) else: # Present up to N suggestions. suggestions = self.spelling_dict.suggest(word) del suggestions[self.config.max_spelling_suggestions :] line_segment = line[word_start_at:] match = re.search(rf"(\W|^)({word})(\W|$)", line_segment) if match: # Start position of second group in regex. col = match.regs[2][0] else: col = line_segment.index(word) col += word_start_at if starts_with_comment: col += 1 indicator = (" " * col) + ("^" * len(word)) all_suggestion = "' or '".join(suggestions) args = (word, original_line, indicator, f"'{all_suggestion}'") self.add_message(msgid, line=line_num, args=args) def process_tokens(self, tokens): if not self.initialized: return # Process tokens and look for comments. for (tok_type, token, (start_row, _), _, _) in tokens: if tok_type == tokenize.COMMENT: if start_row == 1 and token.startswith("#!/"): # Skip shebang lines continue if token.startswith("# pylint:"): # Skip pylint enable/disable comments continue self._check_spelling("wrong-spelling-in-comment", token, start_row) @check_messages("wrong-spelling-in-docstring") def visit_module(self, node: nodes.Module) -> None: if not self.initialized: return self._check_docstring(node) @check_messages("wrong-spelling-in-docstring") def visit_classdef(self, node: nodes.ClassDef) -> None: if not self.initialized: return self._check_docstring(node) @check_messages("wrong-spelling-in-docstring") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if not self.initialized: return self._check_docstring(node) visit_asyncfunctiondef = visit_functiondef def _check_docstring(self, node): """Check the node has any spelling errors.""" docstring = node.doc if not docstring: return start_line = node.lineno + 1 # Go through lines of docstring for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
369
_strip_code_flanked_in_backticks
ref
function
line = _strip_code_flanked_in_backticks(line)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
371
tokenizer
ref
function
for word, word_start_at in self.tokenizer(line.strip()):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
386
check
ref
function
if self.spelling_dict.check(lower_cased_word):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
393
check
ref
function
if self.spelling_dict.check(word):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
396
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
408
suggest
ref
function
suggestions = self.spelling_dict.suggest(word)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
423
add_message
ref
function
self.add_message(msgid, line=line_num, args=args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
425
process_tokens
def
function
def process_tokens(self, tokens): if not self.initialized: return # Process tokens and look for comments. for (tok_type, token, (start_row, _), _, _) in tokens: if tok_type == tokenize.COMMENT: if start_row == 1 and token.startswith("#!/"): # Skip shebang lines continue if token.startswith("# pylint:"): # Skip pylint enable/disable comments continue self._check_spelling("wrong-spelling-in-comment", token, start_row) @check_messages("wrong-spelling-in-docstring") def visit_module(self, node: nodes.Module) -> None: if not self.initialized: return self._check_docstring(node) @check_messages("wrong-spelling-in-docstring") def visit_classdef(self, node: nodes.ClassDef) -> None: if not self.initialized: return self._check_docstring(node) @check_messages("wrong-spelling-in-docstring") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if not self.initialized: return self._check_docstring(node) visit_asyncfunctiondef = visit_functiondef def _check_docstring(self, node): """Check the node has any spelling errors.""" docstring = node.doc if not docstring: return start_line = node.lineno + 1 # Go through lines of docstring for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
438
_check_spelling
ref
function
self._check_spelling("wrong-spelling-in-comment", token, start_row)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
440
check_messages
ref
function
@check_messages("wrong-spelling-in-docstring")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
441
visit_module
def
function
def visit_module(self, node: nodes.Module) -> None: if not self.initialized: return self._check_docstring(node) @check_messages("wrong-spelling-in-docstring") def visit_classdef(self, node: nodes.ClassDef) -> None: if not self.initialized: return self._check_docstring(node) @check_messages("wrong-spelling-in-docstring") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if not self.initialized: return self._check_docstring(node) visit_asyncfunctiondef = visit_functiondef def _check_docstring(self, node): """Check the node has any spelling errors.""" docstring = node.doc if not docstring: return start_line = node.lineno + 1 # Go through lines of docstring for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
444
_check_docstring
ref
function
self._check_docstring(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
446
check_messages
ref
function
@check_messages("wrong-spelling-in-docstring")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
447
visit_classdef
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
450
_check_docstring
ref
function
self._check_docstring(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
452
check_messages
ref
function
@check_messages("wrong-spelling-in-docstring")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
453
visit_functiondef
def
function
def visit_functiondef(self, node: nodes.FunctionDef) -> None: if not self.initialized: return self._check_docstring(node) visit_asyncfunctiondef = visit_functiondef def _check_docstring(self, node): """Check the node has any spelling errors.""" docstring = node.doc if not docstring: return start_line = node.lineno + 1 # Go through lines of docstring for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
456
_check_docstring
ref
function
self._check_docstring(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
460
_check_docstring
def
function
def _check_docstring(self, node): """Check the node has any spelling errors.""" docstring = node.doc if not docstring: return start_line = node.lineno + 1 # Go through lines of docstring for idx, line in enumerate(docstring.splitlines()): self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
470
_check_spelling
ref
function
self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
473
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(SpellingChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
474
register_checker
ref
function
linter.register_checker(SpellingChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/spelling.py
pylint/checkers/spelling.py
474
SpellingChecker
ref
function
linter.register_checker(SpellingChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
317
_check_mode_str
def
function
def _check_mode_str(mode): # check type if not isinstance(mode, str): return _False # check syntax modes = set(mode) _mode = "rwatb+Ux" creating = "x" in modes if modes - set(_mode) or len(mode) > len(modes): return _False # check logic reading = "r" in modes writing = "w" in modes appending = "a" in modes text = "t" in modes binary = "b" in modes if "U" in modes: if writing or appending or creating: return _False reading = _True if text and binary: return _False total = reading + writing + appending + creating if total > 1: return _False if not (reading or writing or appending or creating): return _False return _True
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
347
StdlibChecker
def
class
__init__ _check_bad_thread_instantiation _check_for_preexec_fn_in_popen _check_for_check_kw_in_run _check_shallow_copy_environ visit_call visit_unaryop visit_if visit_ifexp visit_boolop visit_functiondef _check_lru_cache_decorators _check_redundant_assert _check_datetime _check_open_mode _check_open_encoded _check_env_function _check_invalid_envvar_value deprecated_modules deprecated_methods deprecated_arguments deprecated_classes deprecated_decorators
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
489
_check_bad_thread_instantiation
def
function
def _check_bad_thread_instantiation(self, node): if not node.kwargs and not node.keywords and len(node.args) <= 1: self.add_message("bad-thread-instantiation", node=node) def _check_for_preexec_fn_in_popen(self, node): if node.keywords: for keyword in node.keywords: if keyword.arg == "preexec_fn": self.add_message("subprocess-popen-preexec-fn", node=node) def _check_for_check_kw_in_run(self, node): kwargs = {keyword.arg for keyword in (node.keywords or ())} if "check" not in kwargs: self.add_message("subprocess-run-check", node=node) def _check_shallow_copy_environ(self, node: nodes.Call) -> None: arg = utils.get_argument_from_call(node, position=0) try: inferred_args = arg.inferred() except astroid.InferenceError: return for inferred in inferred_args: if inferred.qname() == OS_ENVIRON: self.add_message("shallow-copy-environ", node=node) break @utils.check_messages( "bad-open-mode", "redundant-unittest-assert", "deprecated-method", "deprecated-argument", "bad-thread-instantiation", "shallow-copy-environ", "invalid-envvar-value", "invalid-envvar-default", "subprocess-popen-preexec-fn", "subprocess-run-check", "deprecated-class", "unspecified-encoding", "forgotten-debug-statement", ) def visit_call(self, node: nodes.Call) -> None: """Visit a Call node.""" self.check_deprecated_class_in_call(node) for inferred in utils.infer_all(node.func): if inferred is astroid.Uninferable: continue if inferred.root().name in OPEN_MODULE: if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_MODE ): self._check_open_mode(node) if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_ENCODING or isinstance(node.func, nodes.Attribute) and node.func.attrname in OPEN_FILES_ENCODING ): self._check_open_encoded(node, inferred.root().name) elif inferred.root().name == UNITTEST_CASE: self._check_redundant_assert(node, inferred) elif isinstance(inferred, nodes.ClassDef): if inferred.qname() == THREADING_THREAD: self._check_bad_thread_instantiation(node) elif inferred.qname() == SUBPROCESS_POPEN: self._check_for_preexec_fn_in_popen(node) elif isinstance(inferred, nodes.FunctionDef): name = inferred.qname() if name == COPY_COPY: self._check_shallow_copy_environ(node) elif name in ENV_GETTERS: self._check_env_function(node, inferred) elif name == SUBPROCESS_RUN: self._check_for_check_kw_in_run(node) elif name in DEBUG_BREAKPOINTS: self.add_message("forgotten-debug-statement", node=node) self.check_deprecated_method(node, inferred) @utils.check_messages("boolean-datetime") def visit_unaryop(self, node: nodes.UnaryOp) -> None: if node.op == "not": self._check_datetime(node.operand) @utils.check_messages("boolean-datetime") def visit_if(self, node: nodes.If) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_ifexp(self, node: nodes.IfExp) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_boolop(self, node: nodes.BoolOp) -> None: for value in node.values: self._check_datetime(value) @utils.check_messages("lru-cache-decorating-method") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if node.decorators and isinstance(node.parent, nodes.ClassDef): self._check_lru_cache_decorators(node.decorators) def _check_lru_cache_decorators(self, decorators: nodes.Decorators) -> None: """Check if instance methods are decorated with functools.lru_cache.""" lru_cache_nodes: List[nodes.NodeNG] = [] for d_node in decorators.nodes: try: for infered_node in d_node.infer(): q_name = infered_node.qname() if q_name in NON_INSTANCE_METHODS: return if q_name not in LRU_CACHE: return # Check if there is a maxsize argument to the call if isinstance(d_node, nodes.Call): try: utils.get_argument_from_call( d_node, position=0, keyword="maxsize" ) return except utils.NoSuchArgumentError: pass lru_cache_nodes.append(d_node) break except astroid.InferenceError: pass for lru_cache_node in lru_cache_nodes: self.add_message( "lru-cache-decorating-method", node=lru_cache_node, confidence=interfaces.INFERENCE, ) def _check_redundant_assert(self, node, infer): if ( isinstance(infer, astroid.BoundMethod) and node.args and isinstance(node.args[0], nodes.Const) and infer.name in {"assert_True", "assert_False"} ): self.add_message( "redundant-unittest-assert", args=(infer.name, node.args[0].value), node=node, ) def _check_datetime(self, node): """Check that a datetime was inferred. If so, emit boolean-datetime warning. """ try: inferred = next(node.infer()) except astroid.InferenceError: return if ( isinstance(inferred, astroid.Instance) and inferred.qname() == "datetime.time" ): self.add_message("boolean-datetime", node=node) def _check_open_mode(self, node): """Check that the mode argument of an open or file call is valid.""" try: mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode") except utils.NoSuchArgumentError: return if mode_arg: mode_arg = utils.safe_infer(mode_arg) if isinstance(mode_arg, nodes.Const) and not _check_mode_str( mode_arg.value ): self.add_message( "bad-open-mode", node=node, args=mode_arg.value or str(mode_arg.value), ) def _check_open_encoded(self, node: nodes.Call, open_module: str) -> None: """Check that the encoded argument of an open call is valid.""" mode_arg = None try: if open_module == "_io": mode_arg = utils.get_argument_from_call( node, position=1, keyword="mode" ) elif open_module == "pathlib": mode_arg = utils.get_argument_from_call( node, position=0, keyword="mode" ) except utils.NoSuchArgumentError: pass if mode_arg: mode_arg = utils.safe_infer(mode_arg) if ( not mode_arg or isinstance(mode_arg, nodes.Const) and (not mode_arg.value or "b" not in mode_arg.value) ): encoding_arg = None try: if open_module == "pathlib": if node.func.attrname == "read_text": encoding_arg = utils.get_argument_from_call( node, position=0, keyword="encoding" ) elif node.func.attrname == "write_text": encoding_arg = utils.get_argument_from_call( node, position=1, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=2, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=3, keyword="encoding" ) except utils.NoSuchArgumentError: self.add_message("unspecified-encoding", node=node) if encoding_arg: encoding_arg = utils.safe_infer(encoding_arg) if isinstance(encoding_arg, nodes.Const) and encoding_arg.value is None: self.add_message("unspecified-encoding", node=node) def _check_env_function(self, node, infer): env_name_kwarg = "key" env_value_kwarg = "default" if node.keywords: kwargs = {keyword.arg: keyword.value for keyword in node.keywords} else: kwargs = None if node.args: env_name_arg = node.args[0] elif kwargs and env_name_kwarg in kwargs: env_name_arg = kwargs[env_name_kwarg] else: env_name_arg = None if env_name_arg: self._check_invalid_envvar_value( node=node, message="invalid-envvar-value", call_arg=utils.safe_infer(env_name_arg), infer=infer, allow_none=_False, ) if len(node.args) == 2: env_value_arg = node.args[1] elif kwargs and env_value_kwarg in kwargs: env_value_arg = kwargs[env_value_kwarg] else: env_value_arg = None if env_value_arg: self._check_invalid_envvar_value( node=node, infer=infer, message="invalid-envvar-default", call_arg=utils.safe_infer(env_value_arg), allow_none=_True, ) def _check_invalid_envvar_value(self, node, infer, message, call_arg, allow_none): if call_arg in (astroid.Uninferable, None): return name = infer.qname() if isinstance(call_arg, nodes.Const): emit = _False if call_arg.value is None: emit = not allow_none elif not isinstance(call_arg.value, str): emit = _True if emit: self.add_message(message, node=node, args=(name, call_arg.pytype())) else: self.add_message(message, node=node, args=(name, call_arg.pytype())) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self._deprecated_modules def deprecated_methods(self): return self._deprecated_methods def deprecated_arguments(self, method: str): return self._deprecated_attributes.get(method, ()) def deprecated_classes(self, module: str): return self._deprecated_classes.get(module, ()) def deprecated_decorators(self) -> Iterable: return self._deprecated_decorators
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
491
add_message
ref
function
self.add_message("bad-thread-instantiation", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
493
_check_for_preexec_fn_in_popen
def
function
def _check_for_preexec_fn_in_popen(self, node): if node.keywords: for keyword in node.keywords: if keyword.arg == "preexec_fn": self.add_message("subprocess-popen-preexec-fn", node=node) def _check_for_check_kw_in_run(self, node): kwargs = {keyword.arg for keyword in (node.keywords or ())} if "check" not in kwargs: self.add_message("subprocess-run-check", node=node) def _check_shallow_copy_environ(self, node: nodes.Call) -> None: arg = utils.get_argument_from_call(node, position=0) try: inferred_args = arg.inferred() except astroid.InferenceError: return for inferred in inferred_args: if inferred.qname() == OS_ENVIRON: self.add_message("shallow-copy-environ", node=node) break @utils.check_messages( "bad-open-mode", "redundant-unittest-assert", "deprecated-method", "deprecated-argument", "bad-thread-instantiation", "shallow-copy-environ", "invalid-envvar-value", "invalid-envvar-default", "subprocess-popen-preexec-fn", "subprocess-run-check", "deprecated-class", "unspecified-encoding", "forgotten-debug-statement", ) def visit_call(self, node: nodes.Call) -> None: """Visit a Call node.""" self.check_deprecated_class_in_call(node) for inferred in utils.infer_all(node.func): if inferred is astroid.Uninferable: continue if inferred.root().name in OPEN_MODULE: if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_MODE ): self._check_open_mode(node) if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_ENCODING or isinstance(node.func, nodes.Attribute) and node.func.attrname in OPEN_FILES_ENCODING ): self._check_open_encoded(node, inferred.root().name) elif inferred.root().name == UNITTEST_CASE: self._check_redundant_assert(node, inferred) elif isinstance(inferred, nodes.ClassDef): if inferred.qname() == THREADING_THREAD: self._check_bad_thread_instantiation(node) elif inferred.qname() == SUBPROCESS_POPEN: self._check_for_preexec_fn_in_popen(node) elif isinstance(inferred, nodes.FunctionDef): name = inferred.qname() if name == COPY_COPY: self._check_shallow_copy_environ(node) elif name in ENV_GETTERS: self._check_env_function(node, inferred) elif name == SUBPROCESS_RUN: self._check_for_check_kw_in_run(node) elif name in DEBUG_BREAKPOINTS: self.add_message("forgotten-debug-statement", node=node) self.check_deprecated_method(node, inferred) @utils.check_messages("boolean-datetime") def visit_unaryop(self, node: nodes.UnaryOp) -> None: if node.op == "not": self._check_datetime(node.operand) @utils.check_messages("boolean-datetime") def visit_if(self, node: nodes.If) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_ifexp(self, node: nodes.IfExp) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_boolop(self, node: nodes.BoolOp) -> None: for value in node.values: self._check_datetime(value) @utils.check_messages("lru-cache-decorating-method") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if node.decorators and isinstance(node.parent, nodes.ClassDef): self._check_lru_cache_decorators(node.decorators) def _check_lru_cache_decorators(self, decorators: nodes.Decorators) -> None: """Check if instance methods are decorated with functools.lru_cache.""" lru_cache_nodes: List[nodes.NodeNG] = [] for d_node in decorators.nodes: try: for infered_node in d_node.infer(): q_name = infered_node.qname() if q_name in NON_INSTANCE_METHODS: return if q_name not in LRU_CACHE: return # Check if there is a maxsize argument to the call if isinstance(d_node, nodes.Call): try: utils.get_argument_from_call( d_node, position=0, keyword="maxsize" ) return except utils.NoSuchArgumentError: pass lru_cache_nodes.append(d_node) break except astroid.InferenceError: pass for lru_cache_node in lru_cache_nodes: self.add_message( "lru-cache-decorating-method", node=lru_cache_node, confidence=interfaces.INFERENCE, ) def _check_redundant_assert(self, node, infer): if ( isinstance(infer, astroid.BoundMethod) and node.args and isinstance(node.args[0], nodes.Const) and infer.name in {"assert_True", "assert_False"} ): self.add_message( "redundant-unittest-assert", args=(infer.name, node.args[0].value), node=node, ) def _check_datetime(self, node): """Check that a datetime was inferred. If so, emit boolean-datetime warning. """ try: inferred = next(node.infer()) except astroid.InferenceError: return if ( isinstance(inferred, astroid.Instance) and inferred.qname() == "datetime.time" ): self.add_message("boolean-datetime", node=node) def _check_open_mode(self, node): """Check that the mode argument of an open or file call is valid.""" try: mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode") except utils.NoSuchArgumentError: return if mode_arg: mode_arg = utils.safe_infer(mode_arg) if isinstance(mode_arg, nodes.Const) and not _check_mode_str( mode_arg.value ): self.add_message( "bad-open-mode", node=node, args=mode_arg.value or str(mode_arg.value), ) def _check_open_encoded(self, node: nodes.Call, open_module: str) -> None: """Check that the encoded argument of an open call is valid.""" mode_arg = None try: if open_module == "_io": mode_arg = utils.get_argument_from_call( node, position=1, keyword="mode" ) elif open_module == "pathlib": mode_arg = utils.get_argument_from_call( node, position=0, keyword="mode" ) except utils.NoSuchArgumentError: pass if mode_arg: mode_arg = utils.safe_infer(mode_arg) if ( not mode_arg or isinstance(mode_arg, nodes.Const) and (not mode_arg.value or "b" not in mode_arg.value) ): encoding_arg = None try: if open_module == "pathlib": if node.func.attrname == "read_text": encoding_arg = utils.get_argument_from_call( node, position=0, keyword="encoding" ) elif node.func.attrname == "write_text": encoding_arg = utils.get_argument_from_call( node, position=1, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=2, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=3, keyword="encoding" ) except utils.NoSuchArgumentError: self.add_message("unspecified-encoding", node=node) if encoding_arg: encoding_arg = utils.safe_infer(encoding_arg) if isinstance(encoding_arg, nodes.Const) and encoding_arg.value is None: self.add_message("unspecified-encoding", node=node) def _check_env_function(self, node, infer): env_name_kwarg = "key" env_value_kwarg = "default" if node.keywords: kwargs = {keyword.arg: keyword.value for keyword in node.keywords} else: kwargs = None if node.args: env_name_arg = node.args[0] elif kwargs and env_name_kwarg in kwargs: env_name_arg = kwargs[env_name_kwarg] else: env_name_arg = None if env_name_arg: self._check_invalid_envvar_value( node=node, message="invalid-envvar-value", call_arg=utils.safe_infer(env_name_arg), infer=infer, allow_none=_False, ) if len(node.args) == 2: env_value_arg = node.args[1] elif kwargs and env_value_kwarg in kwargs: env_value_arg = kwargs[env_value_kwarg] else: env_value_arg = None if env_value_arg: self._check_invalid_envvar_value( node=node, infer=infer, message="invalid-envvar-default", call_arg=utils.safe_infer(env_value_arg), allow_none=_True, ) def _check_invalid_envvar_value(self, node, infer, message, call_arg, allow_none): if call_arg in (astroid.Uninferable, None): return name = infer.qname() if isinstance(call_arg, nodes.Const): emit = _False if call_arg.value is None: emit = not allow_none elif not isinstance(call_arg.value, str): emit = _True if emit: self.add_message(message, node=node, args=(name, call_arg.pytype())) else: self.add_message(message, node=node, args=(name, call_arg.pytype())) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self._deprecated_modules def deprecated_methods(self): return self._deprecated_methods def deprecated_arguments(self, method: str): return self._deprecated_attributes.get(method, ()) def deprecated_classes(self, module: str): return self._deprecated_classes.get(module, ()) def deprecated_decorators(self) -> Iterable: return self._deprecated_decorators
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
497
add_message
ref
function
self.add_message("subprocess-popen-preexec-fn", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
499
_check_for_check_kw_in_run
def
function
def _check_for_check_kw_in_run(self, node): kwargs = {keyword.arg for keyword in (node.keywords or ())} if "check" not in kwargs: self.add_message("subprocess-run-check", node=node) def _check_shallow_copy_environ(self, node: nodes.Call) -> None: arg = utils.get_argument_from_call(node, position=0) try: inferred_args = arg.inferred() except astroid.InferenceError: return for inferred in inferred_args: if inferred.qname() == OS_ENVIRON: self.add_message("shallow-copy-environ", node=node) break @utils.check_messages( "bad-open-mode", "redundant-unittest-assert", "deprecated-method", "deprecated-argument", "bad-thread-instantiation", "shallow-copy-environ", "invalid-envvar-value", "invalid-envvar-default", "subprocess-popen-preexec-fn", "subprocess-run-check", "deprecated-class", "unspecified-encoding", "forgotten-debug-statement", ) def visit_call(self, node: nodes.Call) -> None: """Visit a Call node.""" self.check_deprecated_class_in_call(node) for inferred in utils.infer_all(node.func): if inferred is astroid.Uninferable: continue if inferred.root().name in OPEN_MODULE: if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_MODE ): self._check_open_mode(node) if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_ENCODING or isinstance(node.func, nodes.Attribute) and node.func.attrname in OPEN_FILES_ENCODING ): self._check_open_encoded(node, inferred.root().name) elif inferred.root().name == UNITTEST_CASE: self._check_redundant_assert(node, inferred) elif isinstance(inferred, nodes.ClassDef): if inferred.qname() == THREADING_THREAD: self._check_bad_thread_instantiation(node) elif inferred.qname() == SUBPROCESS_POPEN: self._check_for_preexec_fn_in_popen(node) elif isinstance(inferred, nodes.FunctionDef): name = inferred.qname() if name == COPY_COPY: self._check_shallow_copy_environ(node) elif name in ENV_GETTERS: self._check_env_function(node, inferred) elif name == SUBPROCESS_RUN: self._check_for_check_kw_in_run(node) elif name in DEBUG_BREAKPOINTS: self.add_message("forgotten-debug-statement", node=node) self.check_deprecated_method(node, inferred) @utils.check_messages("boolean-datetime") def visit_unaryop(self, node: nodes.UnaryOp) -> None: if node.op == "not": self._check_datetime(node.operand) @utils.check_messages("boolean-datetime") def visit_if(self, node: nodes.If) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_ifexp(self, node: nodes.IfExp) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_boolop(self, node: nodes.BoolOp) -> None: for value in node.values: self._check_datetime(value) @utils.check_messages("lru-cache-decorating-method") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if node.decorators and isinstance(node.parent, nodes.ClassDef): self._check_lru_cache_decorators(node.decorators) def _check_lru_cache_decorators(self, decorators: nodes.Decorators) -> None: """Check if instance methods are decorated with functools.lru_cache.""" lru_cache_nodes: List[nodes.NodeNG] = [] for d_node in decorators.nodes: try: for infered_node in d_node.infer(): q_name = infered_node.qname() if q_name in NON_INSTANCE_METHODS: return if q_name not in LRU_CACHE: return # Check if there is a maxsize argument to the call if isinstance(d_node, nodes.Call): try: utils.get_argument_from_call( d_node, position=0, keyword="maxsize" ) return except utils.NoSuchArgumentError: pass lru_cache_nodes.append(d_node) break except astroid.InferenceError: pass for lru_cache_node in lru_cache_nodes: self.add_message( "lru-cache-decorating-method", node=lru_cache_node, confidence=interfaces.INFERENCE, ) def _check_redundant_assert(self, node, infer): if ( isinstance(infer, astroid.BoundMethod) and node.args and isinstance(node.args[0], nodes.Const) and infer.name in {"assert_True", "assert_False"} ): self.add_message( "redundant-unittest-assert", args=(infer.name, node.args[0].value), node=node, ) def _check_datetime(self, node): """Check that a datetime was inferred. If so, emit boolean-datetime warning. """ try: inferred = next(node.infer()) except astroid.InferenceError: return if ( isinstance(inferred, astroid.Instance) and inferred.qname() == "datetime.time" ): self.add_message("boolean-datetime", node=node) def _check_open_mode(self, node): """Check that the mode argument of an open or file call is valid.""" try: mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode") except utils.NoSuchArgumentError: return if mode_arg: mode_arg = utils.safe_infer(mode_arg) if isinstance(mode_arg, nodes.Const) and not _check_mode_str( mode_arg.value ): self.add_message( "bad-open-mode", node=node, args=mode_arg.value or str(mode_arg.value), ) def _check_open_encoded(self, node: nodes.Call, open_module: str) -> None: """Check that the encoded argument of an open call is valid.""" mode_arg = None try: if open_module == "_io": mode_arg = utils.get_argument_from_call( node, position=1, keyword="mode" ) elif open_module == "pathlib": mode_arg = utils.get_argument_from_call( node, position=0, keyword="mode" ) except utils.NoSuchArgumentError: pass if mode_arg: mode_arg = utils.safe_infer(mode_arg) if ( not mode_arg or isinstance(mode_arg, nodes.Const) and (not mode_arg.value or "b" not in mode_arg.value) ): encoding_arg = None try: if open_module == "pathlib": if node.func.attrname == "read_text": encoding_arg = utils.get_argument_from_call( node, position=0, keyword="encoding" ) elif node.func.attrname == "write_text": encoding_arg = utils.get_argument_from_call( node, position=1, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=2, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=3, keyword="encoding" ) except utils.NoSuchArgumentError: self.add_message("unspecified-encoding", node=node) if encoding_arg: encoding_arg = utils.safe_infer(encoding_arg) if isinstance(encoding_arg, nodes.Const) and encoding_arg.value is None: self.add_message("unspecified-encoding", node=node) def _check_env_function(self, node, infer): env_name_kwarg = "key" env_value_kwarg = "default" if node.keywords: kwargs = {keyword.arg: keyword.value for keyword in node.keywords} else: kwargs = None if node.args: env_name_arg = node.args[0] elif kwargs and env_name_kwarg in kwargs: env_name_arg = kwargs[env_name_kwarg] else: env_name_arg = None if env_name_arg: self._check_invalid_envvar_value( node=node, message="invalid-envvar-value", call_arg=utils.safe_infer(env_name_arg), infer=infer, allow_none=_False, ) if len(node.args) == 2: env_value_arg = node.args[1] elif kwargs and env_value_kwarg in kwargs: env_value_arg = kwargs[env_value_kwarg] else: env_value_arg = None if env_value_arg: self._check_invalid_envvar_value( node=node, infer=infer, message="invalid-envvar-default", call_arg=utils.safe_infer(env_value_arg), allow_none=_True, ) def _check_invalid_envvar_value(self, node, infer, message, call_arg, allow_none): if call_arg in (astroid.Uninferable, None): return name = infer.qname() if isinstance(call_arg, nodes.Const): emit = _False if call_arg.value is None: emit = not allow_none elif not isinstance(call_arg.value, str): emit = _True if emit: self.add_message(message, node=node, args=(name, call_arg.pytype())) else: self.add_message(message, node=node, args=(name, call_arg.pytype())) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self._deprecated_modules def deprecated_methods(self): return self._deprecated_methods def deprecated_arguments(self, method: str): return self._deprecated_attributes.get(method, ()) def deprecated_classes(self, module: str): return self._deprecated_classes.get(module, ()) def deprecated_decorators(self) -> Iterable: return self._deprecated_decorators
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
502
add_message
ref
function
self.add_message("subprocess-run-check", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
504
_check_shallow_copy_environ
def
function
def _check_shallow_copy_environ(self, node: nodes.Call) -> None: arg = utils.get_argument_from_call(node, position=0) try: inferred_args = arg.inferred() except astroid.InferenceError: return for inferred in inferred_args: if inferred.qname() == OS_ENVIRON: self.add_message("shallow-copy-environ", node=node) break @utils.check_messages( "bad-open-mode", "redundant-unittest-assert", "deprecated-method", "deprecated-argument", "bad-thread-instantiation", "shallow-copy-environ", "invalid-envvar-value", "invalid-envvar-default", "subprocess-popen-preexec-fn", "subprocess-run-check", "deprecated-class", "unspecified-encoding", "forgotten-debug-statement", ) def visit_call(self, node: nodes.Call) -> None: """Visit a Call node.""" self.check_deprecated_class_in_call(node) for inferred in utils.infer_all(node.func): if inferred is astroid.Uninferable: continue if inferred.root().name in OPEN_MODULE: if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_MODE ): self._check_open_mode(node) if ( isinstance(node.func, nodes.Name) and node.func.name in OPEN_FILES_ENCODING or isinstance(node.func, nodes.Attribute) and node.func.attrname in OPEN_FILES_ENCODING ): self._check_open_encoded(node, inferred.root().name) elif inferred.root().name == UNITTEST_CASE: self._check_redundant_assert(node, inferred) elif isinstance(inferred, nodes.ClassDef): if inferred.qname() == THREADING_THREAD: self._check_bad_thread_instantiation(node) elif inferred.qname() == SUBPROCESS_POPEN: self._check_for_preexec_fn_in_popen(node) elif isinstance(inferred, nodes.FunctionDef): name = inferred.qname() if name == COPY_COPY: self._check_shallow_copy_environ(node) elif name in ENV_GETTERS: self._check_env_function(node, inferred) elif name == SUBPROCESS_RUN: self._check_for_check_kw_in_run(node) elif name in DEBUG_BREAKPOINTS: self.add_message("forgotten-debug-statement", node=node) self.check_deprecated_method(node, inferred) @utils.check_messages("boolean-datetime") def visit_unaryop(self, node: nodes.UnaryOp) -> None: if node.op == "not": self._check_datetime(node.operand) @utils.check_messages("boolean-datetime") def visit_if(self, node: nodes.If) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_ifexp(self, node: nodes.IfExp) -> None: self._check_datetime(node.test) @utils.check_messages("boolean-datetime") def visit_boolop(self, node: nodes.BoolOp) -> None: for value in node.values: self._check_datetime(value) @utils.check_messages("lru-cache-decorating-method") def visit_functiondef(self, node: nodes.FunctionDef) -> None: if node.decorators and isinstance(node.parent, nodes.ClassDef): self._check_lru_cache_decorators(node.decorators) def _check_lru_cache_decorators(self, decorators: nodes.Decorators) -> None: """Check if instance methods are decorated with functools.lru_cache.""" lru_cache_nodes: List[nodes.NodeNG] = [] for d_node in decorators.nodes: try: for infered_node in d_node.infer(): q_name = infered_node.qname() if q_name in NON_INSTANCE_METHODS: return if q_name not in LRU_CACHE: return # Check if there is a maxsize argument to the call if isinstance(d_node, nodes.Call): try: utils.get_argument_from_call( d_node, position=0, keyword="maxsize" ) return except utils.NoSuchArgumentError: pass lru_cache_nodes.append(d_node) break except astroid.InferenceError: pass for lru_cache_node in lru_cache_nodes: self.add_message( "lru-cache-decorating-method", node=lru_cache_node, confidence=interfaces.INFERENCE, ) def _check_redundant_assert(self, node, infer): if ( isinstance(infer, astroid.BoundMethod) and node.args and isinstance(node.args[0], nodes.Const) and infer.name in {"assert_True", "assert_False"} ): self.add_message( "redundant-unittest-assert", args=(infer.name, node.args[0].value), node=node, ) def _check_datetime(self, node): """Check that a datetime was inferred. If so, emit boolean-datetime warning. """ try: inferred = next(node.infer()) except astroid.InferenceError: return if ( isinstance(inferred, astroid.Instance) and inferred.qname() == "datetime.time" ): self.add_message("boolean-datetime", node=node) def _check_open_mode(self, node): """Check that the mode argument of an open or file call is valid.""" try: mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode") except utils.NoSuchArgumentError: return if mode_arg: mode_arg = utils.safe_infer(mode_arg) if isinstance(mode_arg, nodes.Const) and not _check_mode_str( mode_arg.value ): self.add_message( "bad-open-mode", node=node, args=mode_arg.value or str(mode_arg.value), ) def _check_open_encoded(self, node: nodes.Call, open_module: str) -> None: """Check that the encoded argument of an open call is valid.""" mode_arg = None try: if open_module == "_io": mode_arg = utils.get_argument_from_call( node, position=1, keyword="mode" ) elif open_module == "pathlib": mode_arg = utils.get_argument_from_call( node, position=0, keyword="mode" ) except utils.NoSuchArgumentError: pass if mode_arg: mode_arg = utils.safe_infer(mode_arg) if ( not mode_arg or isinstance(mode_arg, nodes.Const) and (not mode_arg.value or "b" not in mode_arg.value) ): encoding_arg = None try: if open_module == "pathlib": if node.func.attrname == "read_text": encoding_arg = utils.get_argument_from_call( node, position=0, keyword="encoding" ) elif node.func.attrname == "write_text": encoding_arg = utils.get_argument_from_call( node, position=1, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=2, keyword="encoding" ) else: encoding_arg = utils.get_argument_from_call( node, position=3, keyword="encoding" ) except utils.NoSuchArgumentError: self.add_message("unspecified-encoding", node=node) if encoding_arg: encoding_arg = utils.safe_infer(encoding_arg) if isinstance(encoding_arg, nodes.Const) and encoding_arg.value is None: self.add_message("unspecified-encoding", node=node) def _check_env_function(self, node, infer): env_name_kwarg = "key" env_value_kwarg = "default" if node.keywords: kwargs = {keyword.arg: keyword.value for keyword in node.keywords} else: kwargs = None if node.args: env_name_arg = node.args[0] elif kwargs and env_name_kwarg in kwargs: env_name_arg = kwargs[env_name_kwarg] else: env_name_arg = None if env_name_arg: self._check_invalid_envvar_value( node=node, message="invalid-envvar-value", call_arg=utils.safe_infer(env_name_arg), infer=infer, allow_none=_False, ) if len(node.args) == 2: env_value_arg = node.args[1] elif kwargs and env_value_kwarg in kwargs: env_value_arg = kwargs[env_value_kwarg] else: env_value_arg = None if env_value_arg: self._check_invalid_envvar_value( node=node, infer=infer, message="invalid-envvar-default", call_arg=utils.safe_infer(env_value_arg), allow_none=_True, ) def _check_invalid_envvar_value(self, node, infer, message, call_arg, allow_none): if call_arg in (astroid.Uninferable, None): return name = infer.qname() if isinstance(call_arg, nodes.Const): emit = _False if call_arg.value is None: emit = not allow_none elif not isinstance(call_arg.value, str): emit = _True if emit: self.add_message(message, node=node, args=(name, call_arg.pytype())) else: self.add_message(message, node=node, args=(name, call_arg.pytype())) def deprecated_modules(self): """Callback returning the deprecated modules.""" return self._deprecated_modules def deprecated_methods(self): return self._deprecated_methods def deprecated_arguments(self, method: str): return self._deprecated_attributes.get(method, ()) def deprecated_classes(self, module: str): return self._deprecated_classes.get(module, ()) def deprecated_decorators(self) -> Iterable: return self._deprecated_decorators
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/stdlib.py
pylint/checkers/stdlib.py
505
get_argument_from_call
ref
function
arg = utils.get_argument_from_call(node, position=0)