id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
176,972 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast
def only(it):
# type: (Iterable[T]) -> T
if isinstance(it, Sized):
if len(it) != 1:
raise NotOneValueFound('Expected one value, found %s' % len(it))
# noinspection PyTypeChecker
return list(it)[0]
lst = tuple(islice(it, 2))
if len(lst) == 0:
raise NotOneValueFound('Expected one value, found 0')
if len(lst) > 1:
raise NotOneValueFound('Expected one value, found several',lst)
return lst[0]
def walk_both_instructions(original_instructions, original_start, instructions, start):
# type: (List[EnhancedInstruction], int, List[EnhancedInstruction], int) -> Iterator[Tuple[int, EnhancedInstruction, int, EnhancedInstruction]]
"""
Yields matching indices and instructions from the new and original instructions,
leaving out changes made by the sentinel transformation.
"""
original_iter = islice(enumerate(original_instructions), original_start, None)
new_iter = non_sentinel_instructions(instructions, start)
inverted_comparison = False
while True:
try:
original_i, original_inst = next(original_iter)
new_i, new_inst = next(new_iter)
except StopIteration:
return
if (
inverted_comparison
and original_inst.opname != new_inst.opname == "UNARY_NOT"
):
new_i, new_inst = next(new_iter)
inverted_comparison = (
original_inst.opname == new_inst.opname in ("CONTAINS_OP", "IS_OP")
and original_inst.arg != new_inst.arg # type: ignore[attr-defined]
)
yield original_i, original_inst, new_i, new_inst
def find_new_matching(orig_section, instructions):
# type: (List[EnhancedInstruction], List[EnhancedInstruction]) -> Iterator[List[EnhancedInstruction]]
"""
Yields sections of `instructions` which match `orig_section`.
The yielded sections include sentinel instructions, but these
are ignored when checking for matches.
"""
for start in range(len(instructions) - len(orig_section)):
indices, dup_section = zip(
*islice(
non_sentinel_instructions(instructions, start),
len(orig_section),
)
)
if len(dup_section) < len(orig_section):
return
if sections_match(orig_section, dup_section):
yield instructions[start:indices[-1] + 1]
def handle_jump(original_instructions, original_start, instructions, start):
# type: (List[EnhancedInstruction], int, List[EnhancedInstruction], int) -> Optional[List[EnhancedInstruction]]
"""
Returns the section of instructions starting at `start` and ending
with a RETURN_VALUE or RAISE_VARARGS instruction.
There should be a matching section in original_instructions starting at original_start.
If that section doesn't appear elsewhere in original_instructions,
then also delete the returned section of instructions.
"""
for original_j, original_inst, new_j, new_inst in walk_both_instructions(
original_instructions, original_start, instructions, start
):
assert_(opnames_match(original_inst, new_inst))
if original_inst.opname in ("RETURN_VALUE", "RAISE_VARARGS"):
inlined = deepcopy(instructions[start : new_j + 1])
for inl in inlined:
inl._copied = True
orig_section = original_instructions[original_start : original_j + 1]
if not check_duplicates(
original_start, orig_section, original_instructions
):
instructions[start : new_j + 1] = []
return inlined
return None
def opnames_match(inst1, inst2):
# type: (Instruction, Instruction) -> bool
return (
inst1.opname == inst2.opname
or "JUMP" in inst1.opname
and "JUMP" in inst2.opname
or (inst1.opname == "PRINT_EXPR" and inst2.opname == "POP_TOP")
or (
inst1.opname in ("LOAD_METHOD", "LOOKUP_METHOD")
and inst2.opname == "LOAD_ATTR"
)
or (inst1.opname == "CALL_METHOD" and inst2.opname == "CALL_FUNCTION")
)
The provided code snippet includes necessary dependencies for implementing the `handle_jumps` function. Write a Python function `def handle_jumps(instructions, original_instructions)` to solve the following problem:
Transforms instructions in place until it looks more like original_instructions. This is only needed in 3.10+ where optimisations lead to more drastic changes after the sentinel transformation. Replaces JUMP instructions that aren't also present in original_instructions with the sections that they jump to until a raise or return. In some other cases duplication found in `original_instructions` is replicated in `instructions`.
Here is the function:
def handle_jumps(instructions, original_instructions):
# type: (List[EnhancedInstruction], List[EnhancedInstruction]) -> None
"""
Transforms instructions in place until it looks more like original_instructions.
This is only needed in 3.10+ where optimisations lead to more drastic changes
after the sentinel transformation.
Replaces JUMP instructions that aren't also present in original_instructions
with the sections that they jump to until a raise or return.
In some other cases duplication found in `original_instructions`
is replicated in `instructions`.
"""
while True:
for original_i, original_inst, new_i, new_inst in walk_both_instructions(
original_instructions, 0, instructions, 0
):
if opnames_match(original_inst, new_inst):
continue
if "JUMP" in new_inst.opname and "JUMP" not in original_inst.opname:
# Find where the new instruction is jumping to, ignoring
# instructions which have been copied in previous iterations
start = only(
i
for i, inst in enumerate(instructions)
if inst.offset == new_inst.argval
and not getattr(inst, "_copied", False)
)
# Replace the jump instruction with the jumped to section of instructions
# That section may also be deleted if it's not similarly duplicated
# in original_instructions
new_instructions = handle_jump(
original_instructions, original_i, instructions, start
)
assert new_instructions is not None
instructions[new_i : new_i + 1] = new_instructions
else:
# Extract a section of original_instructions from original_i to return/raise
orig_section = []
for section_inst in original_instructions[original_i:]:
orig_section.append(section_inst)
if section_inst.opname in ("RETURN_VALUE", "RAISE_VARARGS"):
break
else:
# No return/raise - this is just a mismatch we can't handle
raise AssertionError
instructions[new_i:new_i] = only(find_new_matching(orig_section, instructions))
# instructions has been modified, the for loop can't sensibly continue
# Restart it from the beginning, checking for other issues
break
else: # No mismatched jumps found, we're done
return | Transforms instructions in place until it looks more like original_instructions. This is only needed in 3.10+ where optimisations lead to more drastic changes after the sentinel transformation. Replaces JUMP instructions that aren't also present in original_instructions with the sections that they jump to until a raise or return. In some other cases duplication found in `original_instructions` is replicated in `instructions`. |
176,973 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast
def get_setter(node):
# type: (EnhancedAST) -> Optional[Callable[[ast.AST], None]]
parent = node.parent
for name, field in ast.iter_fields(parent):
if field is node:
def setter(new_node):
# type: (ast.AST) -> None
return setattr(parent, name, new_node)
return setter
elif isinstance(field, list):
for i, item in enumerate(field):
if item is node:
def setter(new_node):
# type: (ast.AST) -> None
field[i] = new_node
return setter
return None | null |
176,974 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast
def statement_containing_node(node):
# type: (ast.AST) -> EnhancedAST
while not isinstance(node, ast.stmt):
node = cast(EnhancedAST, node).parent
return cast(EnhancedAST, node)
def node_linenos(node):
# type: (ast.AST) -> Iterator[int]
if hasattr(node, "lineno"):
linenos = [] # type: Sequence[int]
if hasattr(node, "end_lineno") and isinstance(node, ast.expr):
assert node.end_lineno is not None # type: ignore[attr-defined]
linenos = range(node.lineno, node.end_lineno + 1) # type: ignore[attr-defined]
else:
linenos = [node.lineno] # type: ignore[attr-defined]
for lineno in linenos:
yield lineno
def assert_linenos(tree):
# type: (ast.AST) -> Iterator[int]
for node in ast.walk(tree):
if (
hasattr(node, 'parent') and
isinstance(statement_containing_node(node), ast.Assert)
):
for lineno in node_linenos(node):
yield lineno | null |
176,975 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast
def is_ipython_cell_code_name(code_name):
def is_ipython_cell_filename(filename):
def is_ipython_cell_code(code_obj):
# type: (types.CodeType) -> bool
return (
is_ipython_cell_filename(code_obj.co_filename) and
is_ipython_cell_code_name(code_obj.co_name)
) | null |
176,976 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast
def _extract_ipython_statement(stmt):
# type: (EnhancedAST) -> ast.Module
# IPython separates each statement in a cell to be executed separately
# So NodeFinder should only compile one statement at a time or it
# will find a code mismatch.
while not isinstance(stmt.parent, ast.Module):
stmt = stmt.parent
# use `ast.parse` instead of `ast.Module` for better portability
# python3.8 changes the signature of `ast.Module`
# Inspired by https://github.com/pallets/werkzeug/pull/1552/files
tree = ast.parse("")
tree.body = [cast(ast.stmt, stmt)]
ast.copy_location(tree, stmt)
return tree
def find_node_ipython(frame, lasti, stmts, source):
# type: (types.FrameType, int, Set[EnhancedAST], Source) -> Tuple[Optional[Any], Optional[Any]]
node = decorator = None
for stmt in stmts:
tree = _extract_ipython_statement(stmt)
try:
node_finder = NodeFinder(frame, stmts, tree, lasti, source)
if (node or decorator) and (node_finder.result or node_finder.decorator):
# Found potential nodes in separate statements,
# cannot resolve ambiguity, give up here
return None, None
node = node_finder.result
decorator = node_finder.decorator
except Exception:
pass
return decorator, node | null |
176,977 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast
The provided code snippet includes necessary dependencies for implementing the `attr_names_match` function. Write a Python function `def attr_names_match(attr, argval)` to solve the following problem:
Checks that the user-visible attr (from ast) can correspond to the argval in the bytecode, i.e. the real attribute fetched internally, which may be mangled for private attributes.
Here is the function:
def attr_names_match(attr, argval):
# type: (str, str) -> bool
"""
Checks that the user-visible attr (from ast) can correspond to
the argval in the bytecode, i.e. the real attribute fetched internally,
which may be mangled for private attributes.
"""
if attr == argval:
return True
if not attr.startswith("__"):
return False
return bool(re.match(r"^_\w+%s$" % attr, argval)) | Checks that the user-visible attr (from ast) can correspond to the argval in the bytecode, i.e. the real attribute fetched internally, which may be mangled for private attributes. |
176,978 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
pycodestyle.register_check(extended_blank_lines)
del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation]
pycodestyle.register_check(continued_indentation)
The provided code snippet includes necessary dependencies for implementing the `extended_blank_lines` function. Write a Python function `def extended_blank_lines(logical_line, blank_lines, blank_before, indent_level, previous_logical)` to solve the following problem:
Check for missing blank lines after class declaration.
Here is the function:
def extended_blank_lines(logical_line,
blank_lines,
blank_before,
indent_level,
previous_logical):
"""Check for missing blank lines after class declaration."""
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({})'.format(blank_lines))
elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
# Missing blank line between class docstring and method declaration.
if (
indent_level and
not blank_lines and
not blank_before and
logical_line.startswith(('def ')) and
'(self' in logical_line
):
yield (0, 'E301 expected 1 blank line, found 0') | Check for missing blank lines after class declaration. |
176,979 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
DEFAULT_INDENT_SIZE = 4
pycodestyle.register_check(extended_blank_lines)
del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation]
pycodestyle.register_check(continued_indentation)
The provided code snippet includes necessary dependencies for implementing the `continued_indentation` function. Write a Python function `def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa)` to solve the following problem:
Override pycodestyle's function to provide indentation information.
Here is the function:
def continued_indentation(logical_line, tokens, indent_level, hang_closing,
indent_char, noqa):
"""Override pycodestyle's function to provide indentation information."""
first_row = tokens[0][2][0]
nrows = 1 + tokens[-1][2][0] - first_row
if noqa or nrows == 1:
return
# indent_next tells us whether the next block is indented. Assuming
# that it is indented by 4 spaces, then we should not allow 4-space
# indents on the final continuation line. In turn, some other
# indents are allowed to have an extra 4 spaces.
indent_next = logical_line.endswith(':')
row = depth = 0
valid_hangs = (
(DEFAULT_INDENT_SIZE,)
if indent_char != '\t' else (DEFAULT_INDENT_SIZE,
2 * DEFAULT_INDENT_SIZE)
)
# Remember how many brackets were opened on each line.
parens = [0] * nrows
# Relative indents of physical lines.
rel_indent = [0] * nrows
# For each depth, collect a list of opening rows.
open_rows = [[0]]
# For each depth, memorize the hanging indentation.
hangs = [None]
# Visual indents.
indent_chances = {}
last_indent = tokens[0][2]
indent = [last_indent[1]]
last_token_multiline = None
line = None
last_line = ''
last_line_begins_with_multiline = False
for token_type, text, start, end, line in tokens:
newline = row < start[0] - first_row
if newline:
row = start[0] - first_row
newline = (not last_token_multiline and
token_type not in (tokenize.NL, tokenize.NEWLINE))
last_line_begins_with_multiline = last_token_multiline
if newline:
# This is the beginning of a continuation line.
last_indent = start
# Record the initial indent.
rel_indent[row] = pycodestyle.expand_indent(line) - indent_level
# Identify closing bracket.
close_bracket = (token_type == tokenize.OP and text in ']})')
# Is the indent relative to an opening bracket line?
for open_row in reversed(open_rows[depth]):
hang = rel_indent[row] - rel_indent[open_row]
hanging_indent = hang in valid_hangs
if hanging_indent:
break
if hangs[depth]:
hanging_indent = (hang == hangs[depth])
visual_indent = (not close_bracket and hang > 0 and
indent_chances.get(start[1]))
if close_bracket and indent[depth]:
# Closing bracket for visual indent.
if start[1] != indent[depth]:
yield (start, 'E124 {}'.format(indent[depth]))
elif close_bracket and not hang:
# closing bracket matches indentation of opening bracket's line
if hang_closing:
yield (start, 'E133 {}'.format(indent[depth]))
elif indent[depth] and start[1] < indent[depth]:
if visual_indent is not True:
# Visual indent is broken.
yield (start, 'E128 {}'.format(indent[depth]))
elif (hanging_indent or
(indent_next and
rel_indent[row] == 2 * DEFAULT_INDENT_SIZE)):
# Hanging indent is verified.
if close_bracket and not hang_closing:
yield (start, 'E123 {}'.format(indent_level +
rel_indent[open_row]))
hangs[depth] = hang
elif visual_indent is True:
# Visual indent is verified.
indent[depth] = start[1]
elif visual_indent in (text, str):
# Ignore token lined up with matching one from a previous line.
pass
else:
one_indented = (indent_level + rel_indent[open_row] +
DEFAULT_INDENT_SIZE)
# Indent is broken.
if hang <= 0:
error = ('E122', one_indented)
elif indent[depth]:
error = ('E127', indent[depth])
elif not close_bracket and hangs[depth]:
error = ('E131', one_indented)
elif hang > DEFAULT_INDENT_SIZE:
error = ('E126', one_indented)
else:
hangs[depth] = hang
error = ('E121', one_indented)
yield (start, '{} {}'.format(*error))
# Look for visual indenting.
if (
parens[row] and
token_type not in (tokenize.NL, tokenize.COMMENT) and
not indent[depth]
):
indent[depth] = start[1]
indent_chances[start[1]] = True
# Deal with implicit string concatenation.
elif (token_type in (tokenize.STRING, tokenize.COMMENT) or
text in ('u', 'ur', 'b', 'br')):
indent_chances[start[1]] = str
# Special case for the "if" statement because len("if (") is equal to
# 4.
elif not indent_chances and not row and not depth and text == 'if':
indent_chances[end[1] + 1] = True
elif text == ':' and line[end[1]:].isspace():
open_rows[depth].append(row)
# Keep track of bracket depth.
if token_type == tokenize.OP:
if text in '([{':
depth += 1
indent.append(0)
hangs.append(None)
if len(open_rows) == depth:
open_rows.append([])
open_rows[depth].append(row)
parens[row] += 1
elif text in ')]}' and depth > 0:
# Parent indents should not be more than this one.
prev_indent = indent.pop() or last_indent[1]
hangs.pop()
for d in range(depth):
if indent[d] > prev_indent:
indent[d] = 0
for ind in list(indent_chances):
if ind >= prev_indent:
del indent_chances[ind]
del open_rows[depth + 1:]
depth -= 1
if depth:
indent_chances[indent[depth]] = True
for idx in range(row, -1, -1):
if parens[idx]:
parens[idx] -= 1
break
assert len(indent) == depth + 1
if (
start[1] not in indent_chances and
# This is for purposes of speeding up E121 (GitHub #90).
not last_line.rstrip().endswith(',')
):
# Allow to line up tokens.
indent_chances[start[1]] = text
last_token_multiline = (start[0] != end[0])
if last_token_multiline:
rel_indent[end[0] - first_row] = rel_indent[row]
last_line = line
if (
indent_next and
not last_line_begins_with_multiline and
pycodestyle.expand_indent(line) == indent_level + DEFAULT_INDENT_SIZE
):
pos = (start[0], indent[0] + 4)
desired_indent = indent_level + 2 * DEFAULT_INDENT_SIZE
if visual_indent:
yield (pos, 'E129 {}'.format(desired_indent))
else:
yield (pos, 'E125 {}'.format(desired_indent)) | Override pycodestyle's function to provide indentation information. |
176,980 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
DOCSTRING_START_REGEX = re.compile(r'^u?r?(?P<kind>["\']{3})')
pycodestyle.register_check(extended_blank_lines)
del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation]
pycodestyle.register_check(continued_indentation)
The provided code snippet includes necessary dependencies for implementing the `get_module_imports_on_top_of_file` function. Write a Python function `def get_module_imports_on_top_of_file(source, import_line_index)` to solve the following problem:
return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function():
Here is the function:
def get_module_imports_on_top_of_file(source, import_line_index):
"""return import or from keyword position
example:
> 0: import sys
1: import os
2:
3: def function():
"""
def is_string_literal(line):
if line[0] in 'uUbB':
line = line[1:]
if line and line[0] in 'rR':
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")
def is_future_import(line):
nodes = ast.parse(line)
for n in nodes.body:
if isinstance(n, ast.ImportFrom) and n.module == '__future__':
return True
return False
def has_future_import(source):
offset = 0
line = ''
for _, next_line in source:
for line_part in next_line.strip().splitlines(True):
line = line + line_part
try:
return is_future_import(line), offset
except SyntaxError:
continue
offset += 1
return False, offset
allowed_try_keywords = ('try', 'except', 'else', 'finally')
in_docstring = False
docstring_kind = '"""'
source_stream = iter(enumerate(source))
for cnt, line in source_stream:
if not in_docstring:
m = DOCSTRING_START_REGEX.match(line.lstrip())
if m is not None:
in_docstring = True
docstring_kind = m.group('kind')
remain = line[m.end(): m.endpos].rstrip()
if remain[-3:] == docstring_kind: # one line doc
in_docstring = False
continue
if in_docstring:
if line.rstrip()[-3:] == docstring_kind:
in_docstring = False
continue
if not line.rstrip():
continue
elif line.startswith('#'):
continue
if line.startswith('import '):
if cnt == import_line_index:
continue
return cnt
elif line.startswith('from '):
if cnt == import_line_index:
continue
hit, offset = has_future_import(
itertools.chain([(cnt, line)], source_stream)
)
if hit:
# move to the back
return cnt + offset + 1
return cnt
elif pycodestyle.DUNDER_REGEX.match(line):
return cnt
elif any(line.startswith(kw) for kw in allowed_try_keywords):
continue
elif is_string_literal(line):
return cnt
else:
return cnt
return 0 | return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function(): |
176,981 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
The provided code snippet includes necessary dependencies for implementing the `get_index_offset_contents` function. Write a Python function `def get_index_offset_contents(result, source)` to solve the following problem:
Return (line_index, column_offset, line_contents).
Here is the function:
def get_index_offset_contents(result, source):
"""Return (line_index, column_offset, line_contents)."""
line_index = result['line'] - 1
return (line_index,
result['column'] - 1,
source[line_index]) | Return (line_index, column_offset, line_contents). |
176,982 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
if sys.platform == 'win32': # pragma: no cover
DEFAULT_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'),
'pycodestyle')
def longest_line_length(code):
"""Return length of longest line."""
if len(code) == 0:
return 0
return max(len(line) for line in code.splitlines())
def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
return ''
def shorten_line(tokens, source, indentation, indent_word, max_line_length,
aggressive=False, experimental=False, previous_line=''):
"""Separate line at OPERATOR.
Multiple candidates will be yielded.
"""
for candidate in _shorten_line(tokens=tokens,
source=source,
indentation=indentation,
indent_word=indent_word,
aggressive=aggressive,
previous_line=previous_line):
yield candidate
if aggressive:
for key_token_strings in SHORTEN_OPERATOR_GROUPS:
shortened = _shorten_line_at_tokens(
tokens=tokens,
source=source,
indentation=indentation,
indent_word=indent_word,
key_token_strings=key_token_strings,
aggressive=aggressive)
if shortened is not None and shortened != source:
yield shortened
if experimental:
for shortened in _shorten_line_at_tokens_new(
tokens=tokens,
source=source,
indentation=indentation,
max_line_length=max_line_length):
yield shortened
def line_shortening_rank(candidate, indent_word, max_line_length,
experimental=False):
"""Return rank of candidate.
This is for sorting candidates.
"""
if not candidate.strip():
return 0
rank = 0
lines = candidate.rstrip().split('\n')
offset = 0
if (
not lines[0].lstrip().startswith('#') and
lines[0].rstrip()[-1] not in '([{'
):
for (opening, closing) in ('()', '[]', '{}'):
# Don't penalize empty containers that aren't split up. Things like
# this "foo(\n )" aren't particularly good.
opening_loc = lines[0].find(opening)
closing_loc = lines[0].find(closing)
if opening_loc >= 0:
if closing_loc < 0 or closing_loc != opening_loc + 1:
offset = max(offset, 1 + opening_loc)
current_longest = max(offset + len(x.strip()) for x in lines)
rank += 4 * max(0, current_longest - max_line_length)
rank += len(lines)
# Too much variation in line length is ugly.
rank += 2 * standard_deviation(len(line) for line in lines)
bad_staring_symbol = {
'(': ')',
'[': ']',
'{': '}'}.get(lines[0][-1])
if len(lines) > 1:
if (
bad_staring_symbol and
lines[1].lstrip().startswith(bad_staring_symbol)
):
rank += 20
for lineno, current_line in enumerate(lines):
current_line = current_line.strip()
if current_line.startswith('#'):
continue
for bad_start in ['.', '%', '+', '-', '/']:
if current_line.startswith(bad_start):
rank += 100
# Do not tolerate operators on their own line.
if current_line == bad_start:
rank += 1000
if (
current_line.endswith(('.', '%', '+', '-', '/')) and
"': " in current_line
):
rank += 1000
if current_line.endswith(('(', '[', '{', '.')):
# Avoid lonely opening. They result in longer lines.
if len(current_line) <= len(indent_word):
rank += 100
# Avoid the ugliness of ", (\n".
if (
current_line.endswith('(') and
current_line[:-1].rstrip().endswith(',')
):
rank += 100
# Avoid the ugliness of "something[\n" and something[index][\n.
if (
current_line.endswith('[') and
len(current_line) > 1 and
(current_line[-2].isalnum() or current_line[-2] in ']')
):
rank += 300
# Also avoid the ugliness of "foo.\nbar"
if current_line.endswith('.'):
rank += 100
if has_arithmetic_operator(current_line):
rank += 100
# Avoid breaking at unary operators.
if re.match(r'.*[(\[{]\s*[\-\+~]$', current_line.rstrip('\\ ')):
rank += 1000
if re.match(r'.*lambda\s*\*$', current_line.rstrip('\\ ')):
rank += 1000
if current_line.endswith(('%', '(', '[', '{')):
rank -= 20
# Try to break list comprehensions at the "for".
if current_line.startswith('for '):
rank -= 50
if current_line.endswith('\\'):
# If a line ends in \-newline, it may be part of a
# multiline string. In that case, we would like to know
# how long that line is without the \-newline. If it's
# longer than the maximum, or has comments, then we assume
# that the \-newline is an okay candidate and only
# penalize it a bit.
total_len = len(current_line)
lineno += 1
while lineno < len(lines):
total_len += len(lines[lineno])
if lines[lineno].lstrip().startswith('#'):
total_len = max_line_length
break
if not lines[lineno].endswith('\\'):
break
lineno += 1
if total_len < max_line_length:
rank += 10
else:
rank += 100 if experimental else 1
# Prefer breaking at commas rather than colon.
if ',' in current_line and current_line.endswith(':'):
rank += 10
# Avoid splitting dictionaries between key and value.
if current_line.endswith(':'):
rank += 100
rank += 10 * count_unbalanced_brackets(current_line)
return max(0, rank)
def wrap_output(output, encoding):
"""Return output with specified encoding."""
return codecs.getwriter(encoding)(output.buffer
if hasattr(output, 'buffer')
else output)
generate_tokens = _cached_tokenizer.generate_tokens
The provided code snippet includes necessary dependencies for implementing the `get_fixed_long_line` function. Write a Python function `def get_fixed_long_line(target, previous_line, original, indent_word=' ', max_line_length=79, aggressive=False, experimental=False, verbose=False)` to solve the following problem:
Break up long line and return result. Do this by generating multiple reformatted candidates and then ranking the candidates to heuristically select the best option.
Here is the function:
def get_fixed_long_line(target, previous_line, original,
indent_word=' ', max_line_length=79,
aggressive=False, experimental=False, verbose=False):
"""Break up long line and return result.
Do this by generating multiple reformatted candidates and then
ranking the candidates to heuristically select the best option.
"""
indent = _get_indentation(target)
source = target[len(indent):]
assert source.lstrip() == source
assert not target.lstrip().startswith('#')
# Check for partial multiline.
tokens = list(generate_tokens(source))
candidates = shorten_line(
tokens, source, indent,
indent_word,
max_line_length,
aggressive=aggressive,
experimental=experimental,
previous_line=previous_line)
# Also sort alphabetically as a tie breaker (for determinism).
candidates = sorted(
sorted(set(candidates).union([target, original])),
key=lambda x: line_shortening_rank(
x,
indent_word,
max_line_length,
experimental=experimental))
if verbose >= 4:
print(('-' * 79 + '\n').join([''] + candidates + ['']),
file=wrap_output(sys.stderr, 'utf-8'))
if candidates:
best_candidate = candidates[0]
# Don't allow things to get longer.
if longest_line_length(best_candidate) > longest_line_length(original):
return None
return best_candidate | Break up long line and return result. Do this by generating multiple reformatted candidates and then ranking the candidates to heuristically select the best option. |
176,983 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
def untokenize_without_newlines(tokens):
"""Return source code based on tokens."""
text = ''
last_row = 0
last_column = -1
for t in tokens:
token_string = t[1]
(start_row, start_column) = t[2]
(end_row, end_column) = t[3]
if start_row > last_row:
last_column = 0
if (
(start_column > last_column or token_string == '\n') and
not text.endswith(' ')
):
text += ' '
if token_string != '\n':
text += token_string
last_row = end_row
last_column = end_column
return text.rstrip()
def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
return ''
generate_tokens = _cached_tokenizer.generate_tokens
The provided code snippet includes necessary dependencies for implementing the `join_logical_line` function. Write a Python function `def join_logical_line(logical_line)` to solve the following problem:
Return single line based on logical line input.
Here is the function:
def join_logical_line(logical_line):
"""Return single line based on logical line input."""
indentation = _get_indentation(logical_line)
return indentation + untokenize_without_newlines(
generate_tokens(logical_line.lstrip())) + '\n' | Return single line based on logical line input. |
176,984 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
generate_tokens = _cached_tokenizer.generate_tokens
def _find_logical(source_lines):
# Make a variable which is the index of all the starts of lines.
logical_start = []
logical_end = []
last_newline = True
parens = 0
for t in generate_tokens(''.join(source_lines)):
if t[0] in [tokenize.COMMENT, tokenize.DEDENT,
tokenize.INDENT, tokenize.NL,
tokenize.ENDMARKER]:
continue
if not parens and t[0] in [tokenize.NEWLINE, tokenize.SEMI]:
last_newline = True
logical_end.append((t[3][0] - 1, t[2][1]))
continue
if last_newline and not parens:
logical_start.append((t[2][0] - 1, t[2][1]))
last_newline = False
if t[0] == tokenize.OP:
if t[1] in '([{':
parens += 1
elif t[1] in '}])':
parens -= 1
return (logical_start, logical_end) | null |
176,985 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
The provided code snippet includes necessary dependencies for implementing the `_get_logical` function. Write a Python function `def _get_logical(source_lines, result, logical_start, logical_end)` to solve the following problem:
Return the logical line corresponding to the result. Assumes input is already E702-clean.
Here is the function:
def _get_logical(source_lines, result, logical_start, logical_end):
"""Return the logical line corresponding to the result.
Assumes input is already E702-clean.
"""
row = result['line'] - 1
col = result['column'] - 1
ls = None
le = None
for i in range(0, len(logical_start), 1):
assert logical_end
x = logical_end[i]
if x[0] > row or (x[0] == row and x[1] > col):
le = x
ls = logical_start[i]
break
if ls is None:
return None
original = source_lines[ls[0]:le[0] + 1]
return ls, le, original | Return the logical line corresponding to the result. Assumes input is already E702-clean. |
176,986 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
def split_and_strip_non_empty_lines(text):
"""Return lines split by newline.
Ignore empty lines.
"""
return [line.strip() for line in text.splitlines() if line.strip()]
The provided code snippet includes necessary dependencies for implementing the `code_almost_equal` function. Write a Python function `def code_almost_equal(a, b)` to solve the following problem:
Return True if code is similar. Ignore whitespace when comparing specific line.
Here is the function:
def code_almost_equal(a, b):
"""Return True if code is similar.
Ignore whitespace when comparing specific line.
"""
split_a = split_and_strip_non_empty_lines(a)
split_b = split_and_strip_non_empty_lines(b)
if len(split_a) != len(split_b):
return False
for (index, _) in enumerate(split_a):
if ''.join(split_a[index].split()) != ''.join(split_b[index].split()):
return False
return True | Return True if code is similar. Ignore whitespace when comparing specific line. |
176,987 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
generate_tokens = _cached_tokenizer.generate_tokens
The provided code snippet includes necessary dependencies for implementing the `_get_indentword` function. Write a Python function `def _get_indentword(source)` to solve the following problem:
Return indentation type.
Here is the function:
def _get_indentword(source):
"""Return indentation type."""
indent_word = ' ' # Default in case source has no indentation
try:
for t in generate_tokens(source):
if t[0] == token.INDENT:
indent_word = t[1]
break
except (SyntaxError, tokenize.TokenError):
pass
return indent_word | Return indentation type. |
176,988 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
The provided code snippet includes necessary dependencies for implementing the `_priority_key` function. Write a Python function `def _priority_key(pep8_result)` to solve the following problem:
Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation.
Here is the function:
def _priority_key(pep8_result):
"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation.
"""
priority = [
# Fix multiline colon-based before semicolon based.
'e701',
# Break multiline statements early.
'e702',
# Things that make lines longer.
'e225', 'e231',
# Remove extraneous whitespace before breaking lines.
'e201',
# Shorten whitespace in comment before resorting to wrapping.
'e262'
]
middle_index = 10000
lowest_priority = [
# We need to shorten lines last since the logical fixer can get in a
# loop, which causes us to exit early.
'e501',
]
key = pep8_result['id'].lower()
try:
return priority.index(key)
except ValueError:
try:
return middle_index + lowest_priority.index(key) + 1
except ValueError:
return middle_index | Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation. |
176,989 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
def _is_binary_operator(token_type, text):
return ((token_type == tokenize.OP or text in ['and', 'or']) and
text not in '()[]{},:.;@=%~') | null |
176,990 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
The provided code snippet includes necessary dependencies for implementing the `fix_whitespace` function. Write a Python function `def fix_whitespace(line, offset, replacement)` to solve the following problem:
Replace whitespace at offset and return fixed line.
Here is the function:
def fix_whitespace(line, offset, replacement):
"""Replace whitespace at offset and return fixed line."""
# Replace escaped newlines too
left = line[:offset].rstrip('\n\r \t\\')
right = line[offset:].lstrip('\n\r \t\\')
if right.startswith('#'):
return line
return left + replacement + right | Replace whitespace at offset and return fixed line. |
176,991 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
pycodestyle.register_check(extended_blank_lines)
del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation]
pycodestyle.register_check(continued_indentation)
The provided code snippet includes necessary dependencies for implementing the `_execute_pep8` function. Write a Python function `def _execute_pep8(pep8_options, source)` to solve the following problem:
Execute pycodestyle via python method calls.
Here is the function:
def _execute_pep8(pep8_options, source):
"""Execute pycodestyle via python method calls."""
class QuietReport(pycodestyle.BaseReport):
"""Version of checker that does not print."""
def __init__(self, options):
super(QuietReport, self).__init__(options)
self.__full_error_results = []
def error(self, line_number, offset, text, check):
"""Collect errors."""
code = super(QuietReport, self).error(line_number,
offset,
text,
check)
if code:
self.__full_error_results.append(
{'id': code,
'line': line_number,
'column': offset + 1,
'info': text})
def full_error_results(self):
"""Return error results in detail.
Results are in the form of a list of dictionaries. Each
dictionary contains 'id', 'line', 'column', and 'info'.
"""
return self.__full_error_results
checker = pycodestyle.Checker('', lines=source, reporter=QuietReport,
**pep8_options)
checker.check_all()
return checker.report.full_error_results() | Execute pycodestyle via python method calls. |
176,992 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
CR = '\r'
LF = '\n'
def _remove_leading_and_normalize(line, with_rstrip=True):
# ignore FF in first lstrip()
if with_rstrip:
return line.lstrip(' \t\v').rstrip(CR + LF) + '\n'
return line.lstrip(' \t\v') | null |
176,993 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
The provided code snippet includes necessary dependencies for implementing the `_reindent_stats` function. Write a Python function `def _reindent_stats(tokens)` to solve the following problem:
Return list of (lineno, indentlevel) pairs. One for each stmt and comment line. indentlevel is -1 for comment lines, as a signal that tokenize doesn't know what to do about them; indeed, they're our headache!
Here is the function:
def _reindent_stats(tokens):
"""Return list of (lineno, indentlevel) pairs.
One for each stmt and comment line. indentlevel is -1 for comment
lines, as a signal that tokenize doesn't know what to do about them;
indeed, they're our headache!
"""
find_stmt = 1 # Next token begins a fresh stmt?
level = 0 # Current indent level.
stats = []
for t in tokens:
token_type = t[0]
sline = t[2][0]
line = t[4]
if token_type == tokenize.NEWLINE:
# A program statement, or ENDMARKER, will eventually follow,
# after some (possibly empty) run of tokens of the form
# (NL | COMMENT)* (INDENT | DEDENT+)?
find_stmt = 1
elif token_type == tokenize.INDENT:
find_stmt = 1
level += 1
elif token_type == tokenize.DEDENT:
find_stmt = 1
level -= 1
elif token_type == tokenize.COMMENT:
if find_stmt:
stats.append((sline, -1))
# But we're still looking for a new stmt, so leave
# find_stmt alone.
elif token_type == tokenize.NL:
pass
elif find_stmt:
# This is the first "real token" following a NEWLINE, so it
# must be the first token of the next program statement, or an
# ENDMARKER.
find_stmt = 0
if line: # Not endmarker.
stats.append((sline, level))
return stats | Return list of (lineno, indentlevel) pairs. One for each stmt and comment line. indentlevel is -1 for comment lines, as a signal that tokenize doesn't know what to do about them; indeed, they're our headache! |
176,994 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
The provided code snippet includes necessary dependencies for implementing the `_leading_space_count` function. Write a Python function `def _leading_space_count(line)` to solve the following problem:
Return number of leading spaces in line.
Here is the function:
def _leading_space_count(line):
"""Return number of leading spaces in line."""
i = 0
while i < len(line) and line[i] == ' ':
i += 1
return i | Return number of leading spaces in line. |
176,995 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
def get_disabled_ranges(source):
"""Returns a list of tuples representing the disabled ranges.
If disabled and no re-enable will disable for rest of file.
"""
enable_line_nums = find_with_line_numbers(ENABLE_REGEX, source)
disable_line_nums = find_with_line_numbers(DISABLE_REGEX, source)
total_lines = len(re.findall("\n", source)) + 1
enable_commands = {}
for num in enable_line_nums:
enable_commands[num] = True
for num in disable_line_nums:
enable_commands[num] = False
disabled_ranges = []
currently_enabled = True
disabled_start = None
for line, commanded_enabled in sorted(enable_commands.items()):
if commanded_enabled is False and currently_enabled is True:
disabled_start = line
currently_enabled = False
elif commanded_enabled is True and currently_enabled is False:
disabled_ranges.append((disabled_start, line))
currently_enabled = True
if currently_enabled is False:
disabled_ranges.append((disabled_start, total_lines))
return disabled_ranges
def filter_disabled_results(result, disabled_ranges):
"""Filter out reports based on tuple of disabled ranges.
"""
line = result['line']
for disabled_range in disabled_ranges:
if disabled_range[0] <= line <= disabled_range[1]:
return False
return True
def multiline_string_lines(source, include_docstrings=False):
"""Return line numbers that are within multiline strings.
The line numbers are indexed at 1.
Docstrings are ignored.
"""
line_numbers = set()
previous_token_type = ''
try:
for t in generate_tokens(source):
token_type = t[0]
start_row = t[2][0]
end_row = t[3][0]
if token_type == tokenize.STRING and start_row != end_row:
if (
include_docstrings or
previous_token_type != tokenize.INDENT
):
# We increment by one since we want the contents of the
# string.
line_numbers |= set(range(1 + start_row, 1 + end_row))
previous_token_type = token_type
except (SyntaxError, tokenize.TokenError):
pass
return line_numbers
def commented_out_code_lines(source):
"""Return line numbers of comments that are likely code.
Commented-out code is bad practice, but modifying it just adds even
more clutter.
"""
line_numbers = []
try:
for t in generate_tokens(source):
token_type = t[0]
token_string = t[1]
start_row = t[2][0]
line = t[4]
# Ignore inline comments.
if not line.lstrip().startswith('#'):
continue
if token_type == tokenize.COMMENT:
stripped_line = token_string.lstrip('#').strip()
with warnings.catch_warnings():
# ignore SyntaxWarning in Python3.8+
# refs:
# https://bugs.python.org/issue15248
# https://docs.python.org/3.8/whatsnew/3.8.html#other-language-changes
warnings.filterwarnings("ignore", category=SyntaxWarning)
if (
' ' in stripped_line and
'#' not in stripped_line and
check_syntax(stripped_line)
):
line_numbers.append(start_row)
except (SyntaxError, tokenize.TokenError):
pass
return line_numbers
The provided code snippet includes necessary dependencies for implementing the `filter_results` function. Write a Python function `def filter_results(source, results, aggressive)` to solve the following problem:
Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712).
Here is the function:
def filter_results(source, results, aggressive):
"""Filter out spurious reports from pycodestyle.
If aggressive is True, we allow possibly unsafe fixes (E711, E712).
"""
non_docstring_string_line_numbers = multiline_string_lines(
source, include_docstrings=False)
all_string_line_numbers = multiline_string_lines(
source, include_docstrings=True)
commented_out_code_line_numbers = commented_out_code_lines(source)
# Filter out the disabled ranges
disabled_ranges = get_disabled_ranges(source)
if disabled_ranges:
results = [
result for result in results if filter_disabled_results(
result,
disabled_ranges,
)
]
has_e901 = any(result['id'].lower() == 'e901' for result in results)
for r in results:
issue_id = r['id'].lower()
if r['line'] in non_docstring_string_line_numbers:
if issue_id.startswith(('e1', 'e501', 'w191')):
continue
if r['line'] in all_string_line_numbers:
if issue_id in ['e501']:
continue
# We must offset by 1 for lines that contain the trailing contents of
# multiline strings.
if not aggressive and (r['line'] + 1) in all_string_line_numbers:
# Do not modify multiline strings in non-aggressive mode. Remove
# trailing whitespace could break doctests.
if issue_id.startswith(('w29', 'w39')):
continue
if aggressive <= 0:
if issue_id.startswith(('e711', 'e72', 'w6')):
continue
if aggressive <= 1:
if issue_id.startswith(('e712', 'e713', 'e714')):
continue
if aggressive <= 2:
if issue_id.startswith(('e704')):
continue
if r['line'] in commented_out_code_line_numbers:
if issue_id.startswith(('e261', 'e262', 'e501')):
continue
# Do not touch indentation if there is a token error caused by
# incomplete multi-line statement. Otherwise, we risk screwing up the
# indentation.
if has_e901:
if issue_id.startswith(('e1', 'e7')):
continue
yield r | Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712). |
176,996 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
return ''
The provided code snippet includes necessary dependencies for implementing the `shorten_comment` function. Write a Python function `def shorten_comment(line, max_line_length, last_comment=False)` to solve the following problem:
Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text.
Here is the function:
def shorten_comment(line, max_line_length, last_comment=False):
"""Return trimmed or split long comment line.
If there are no comments immediately following it, do a text wrap.
Doing this wrapping on all comments in general would lead to jagged
comment text.
"""
assert len(line) > max_line_length
line = line.rstrip()
# PEP 8 recommends 72 characters for comment text.
indentation = _get_indentation(line) + '# '
max_line_length = min(max_line_length,
len(indentation) + 72)
MIN_CHARACTER_REPEAT = 5
if (
len(line) - len(line.rstrip(line[-1])) >= MIN_CHARACTER_REPEAT and
not line[-1].isalnum()
):
# Trim comments that end with things like ---------
return line[:max_line_length] + '\n'
elif last_comment and re.match(r'\s*#+\s*\w+', line):
split_lines = textwrap.wrap(line.lstrip(' \t#'),
initial_indent=indentation,
subsequent_indent=indentation,
width=max_line_length,
break_long_words=False,
break_on_hyphens=False)
return '\n'.join(split_lines) + '\n'
return line + '\n' | Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text. |
176,997 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
def _get_options(raw_options, apply_config):
"""Return parsed options."""
if not raw_options:
return parse_args([''], apply_config=apply_config)
if isinstance(raw_options, dict):
options = parse_args([''], apply_config=apply_config)
for name, value in raw_options.items():
if not hasattr(options, name):
raise ValueError("No such option '{}'".format(name))
# Check for very basic type errors.
expected_type = type(getattr(options, name))
if not isinstance(expected_type, (str, )):
if isinstance(value, (str, )):
raise ValueError(
"Option '{}' should not be a string".format(name))
setattr(options, name, value)
else:
options = raw_options
return options
def fix_lines(source_lines, options, filename=''):
"""Return fixed source code."""
# Transform everything to line feed. Then change them back to original
# before returning fixed source code.
original_newline = find_newline(source_lines)
tmp_source = ''.join(normalize_line_endings(source_lines, '\n'))
# Keep a history to break out of cycles.
previous_hashes = set()
if options.line_range:
# Disable "apply_local_fixes()" for now due to issue #175.
fixed_source = tmp_source
else:
# Apply global fixes only once (for efficiency).
fixed_source = apply_global_fixes(tmp_source,
options,
filename=filename)
passes = 0
long_line_ignore_cache = set()
while hash(fixed_source) not in previous_hashes:
if options.pep8_passes >= 0 and passes > options.pep8_passes:
break
passes += 1
previous_hashes.add(hash(fixed_source))
tmp_source = copy.copy(fixed_source)
fix = FixPEP8(
filename,
options,
contents=tmp_source,
long_line_ignore_cache=long_line_ignore_cache)
fixed_source = fix.fix()
sio = io.StringIO(fixed_source)
return ''.join(normalize_line_endings(sio.readlines(), original_newline))
def get_encoding():
"""Return preferred encoding."""
return locale.getpreferredencoding() or sys.getdefaultencoding()
The provided code snippet includes necessary dependencies for implementing the `fix_code` function. Write a Python function `def fix_code(source, options=None, encoding=None, apply_config=False)` to solve the following problem:
Return fixed source code. "encoding" will be used to decode "source" if it is a byte string.
Here is the function:
def fix_code(source, options=None, encoding=None, apply_config=False):
"""Return fixed source code.
"encoding" will be used to decode "source" if it is a byte string.
"""
options = _get_options(options, apply_config)
# normalize
options.ignore = [opt.upper() for opt in options.ignore]
options.select = [opt.upper() for opt in options.select]
# check ignore args
# NOTE: If W50x is not included, add W50x because the code
# correction result is indefinite.
ignore_opt = options.ignore
if not {"W50", "W503", "W504"} & set(ignore_opt):
options.ignore.append("W50")
if not isinstance(source, str):
source = source.decode(encoding or get_encoding())
sio = io.StringIO(source)
return fix_lines(sio.readlines(), options=options) | Return fixed source code. "encoding" will be used to decode "source" if it is a byte string. |
176,998 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
CODE_TO_2TO3 = {
'E231': ['ws_comma'],
'E721': ['idioms'],
'W690': ['apply',
'except',
'exitfunc',
'numliterals',
'operator',
'paren',
'reduce',
'renames',
'standarderror',
'sys_exc',
'throw',
'tuple_params',
'xreadlines']}
class FixPEP8(object):
"""Fix invalid code.
Fixer methods are prefixed "fix_". The _fix_source() method looks for these
automatically.
The fixer method can take either one or two arguments (in addition to
self). The first argument is "result", which is the error information from
pycodestyle. The second argument, "logical", is required only for
logical-line fixes.
The fixer method can return the list of modified lines or None. An empty
list would mean that no changes were made. None would mean that only the
line reported in the pycodestyle error was modified. Note that the modified
line numbers that are returned are indexed at 1. This typically would
correspond with the line number reported in the pycodestyle error
information.
[fixed method list]
- e111,e114,e115,e116
- e121,e122,e123,e124,e125,e126,e127,e128,e129
- e201,e202,e203
- e211
- e221,e222,e223,e224,e225
- e231
- e251,e252
- e261,e262
- e271,e272,e273,e274,e275
- e301,e302,e303,e304,e305,e306
- e401,e402
- e502
- e701,e702,e703,e704
- e711,e712,e713,e714
- e722
- e731
- w291
- w503,504
"""
def __init__(self, filename,
options,
contents=None,
long_line_ignore_cache=None):
self.filename = filename
if contents is None:
self.source = readlines_from_file(filename)
else:
sio = io.StringIO(contents)
self.source = sio.readlines()
self.options = options
self.indent_word = _get_indentword(''.join(self.source))
# collect imports line
self.imports = {}
for i, line in enumerate(self.source):
if (line.find("import ") == 0 or line.find("from ") == 0) and \
line not in self.imports:
# collect only import statements that first appeared
self.imports[line] = i
self.long_line_ignore_cache = (
set() if long_line_ignore_cache is None
else long_line_ignore_cache)
# Many fixers are the same even though pycodestyle categorizes them
# differently.
self.fix_e115 = self.fix_e112
self.fix_e121 = self._fix_reindent
self.fix_e122 = self._fix_reindent
self.fix_e123 = self._fix_reindent
self.fix_e124 = self._fix_reindent
self.fix_e126 = self._fix_reindent
self.fix_e127 = self._fix_reindent
self.fix_e128 = self._fix_reindent
self.fix_e129 = self._fix_reindent
self.fix_e133 = self.fix_e131
self.fix_e202 = self.fix_e201
self.fix_e203 = self.fix_e201
self.fix_e211 = self.fix_e201
self.fix_e221 = self.fix_e271
self.fix_e222 = self.fix_e271
self.fix_e223 = self.fix_e271
self.fix_e226 = self.fix_e225
self.fix_e227 = self.fix_e225
self.fix_e228 = self.fix_e225
self.fix_e241 = self.fix_e271
self.fix_e242 = self.fix_e224
self.fix_e252 = self.fix_e225
self.fix_e261 = self.fix_e262
self.fix_e272 = self.fix_e271
self.fix_e273 = self.fix_e271
self.fix_e274 = self.fix_e271
self.fix_e275 = self.fix_e271
self.fix_e306 = self.fix_e301
self.fix_e501 = (
self.fix_long_line_logically if
options and (options.aggressive >= 2 or options.experimental) else
self.fix_long_line_physically)
self.fix_e703 = self.fix_e702
self.fix_w292 = self.fix_w291
self.fix_w293 = self.fix_w291
def _fix_source(self, results):
try:
(logical_start, logical_end) = _find_logical(self.source)
logical_support = True
except (SyntaxError, tokenize.TokenError): # pragma: no cover
logical_support = False
completed_lines = set()
for result in sorted(results, key=_priority_key):
if result['line'] in completed_lines:
continue
fixed_methodname = 'fix_' + result['id'].lower()
if hasattr(self, fixed_methodname):
fix = getattr(self, fixed_methodname)
line_index = result['line'] - 1
original_line = self.source[line_index]
is_logical_fix = len(_get_parameters(fix)) > 2
if is_logical_fix:
logical = None
if logical_support:
logical = _get_logical(self.source,
result,
logical_start,
logical_end)
if logical and set(range(
logical[0][0] + 1,
logical[1][0] + 1)).intersection(
completed_lines):
continue
modified_lines = fix(result, logical)
else:
modified_lines = fix(result)
if modified_lines is None:
# Force logical fixes to report what they modified.
assert not is_logical_fix
if self.source[line_index] == original_line:
modified_lines = []
if modified_lines:
completed_lines.update(modified_lines)
elif modified_lines == []: # Empty list means no fix
if self.options.verbose >= 2:
print(
'---> Not fixing {error} on line {line}'.format(
error=result['id'], line=result['line']),
file=sys.stderr)
else: # We assume one-line fix when None.
completed_lines.add(result['line'])
else:
if self.options.verbose >= 3:
print(
"---> '{}' is not defined.".format(fixed_methodname),
file=sys.stderr)
info = result['info'].strip()
print('---> {}:{}:{}:{}'.format(self.filename,
result['line'],
result['column'],
info),
file=sys.stderr)
def fix(self):
"""Return a version of the source code with PEP 8 violations fixed."""
pep8_options = {
'ignore': self.options.ignore,
'select': self.options.select,
'max_line_length': self.options.max_line_length,
'hang_closing': self.options.hang_closing,
}
results = _execute_pep8(pep8_options, self.source)
if self.options.verbose:
progress = {}
for r in results:
if r['id'] not in progress:
progress[r['id']] = set()
progress[r['id']].add(r['line'])
print('---> {n} issue(s) to fix {progress}'.format(
n=len(results), progress=progress), file=sys.stderr)
if self.options.line_range:
start, end = self.options.line_range
results = [r for r in results
if start <= r['line'] <= end]
self._fix_source(filter_results(source=''.join(self.source),
results=results,
aggressive=self.options.aggressive))
if self.options.line_range:
# If number of lines has changed then change line_range.
count = sum(sline.count('\n')
for sline in self.source[start - 1:end])
self.options.line_range[1] = start + count - 1
return ''.join(self.source)
def _fix_reindent(self, result):
"""Fix a badly indented line.
This is done by adding or removing from its initial indent only.
"""
num_indent_spaces = int(result['info'].split()[1])
line_index = result['line'] - 1
target = self.source[line_index]
self.source[line_index] = ' ' * num_indent_spaces + target.lstrip()
def fix_e112(self, result):
"""Fix under-indented comments."""
line_index = result['line'] - 1
target = self.source[line_index]
if not target.lstrip().startswith('#'):
# Don't screw with invalid syntax.
return []
self.source[line_index] = self.indent_word + target
def fix_e113(self, result):
"""Fix unexpected indentation."""
line_index = result['line'] - 1
target = self.source[line_index]
indent = _get_indentation(target)
stripped = target.lstrip()
self.source[line_index] = indent[1:] + stripped
def fix_e116(self, result):
"""Fix over-indented comments."""
line_index = result['line'] - 1
target = self.source[line_index]
indent = _get_indentation(target)
stripped = target.lstrip()
if not stripped.startswith('#'):
# Don't screw with invalid syntax.
return []
self.source[line_index] = indent[1:] + stripped
def fix_e117(self, result):
"""Fix over-indented."""
line_index = result['line'] - 1
target = self.source[line_index]
indent = _get_indentation(target)
if indent == '\t':
return []
stripped = target.lstrip()
self.source[line_index] = indent[1:] + stripped
def fix_e125(self, result):
"""Fix indentation undistinguish from the next logical line."""
num_indent_spaces = int(result['info'].split()[1])
line_index = result['line'] - 1
target = self.source[line_index]
spaces_to_add = num_indent_spaces - len(_get_indentation(target))
indent = len(_get_indentation(target))
modified_lines = []
while len(_get_indentation(self.source[line_index])) >= indent:
self.source[line_index] = (' ' * spaces_to_add +
self.source[line_index])
modified_lines.append(1 + line_index) # Line indexed at 1.
line_index -= 1
return modified_lines
def fix_e131(self, result):
"""Fix indentation undistinguish from the next logical line."""
num_indent_spaces = int(result['info'].split()[1])
line_index = result['line'] - 1
target = self.source[line_index]
spaces_to_add = num_indent_spaces - len(_get_indentation(target))
indent_length = len(_get_indentation(target))
spaces_to_add = num_indent_spaces - indent_length
if num_indent_spaces == 0 and indent_length == 0:
spaces_to_add = 4
if spaces_to_add >= 0:
self.source[line_index] = (' ' * spaces_to_add +
self.source[line_index])
else:
offset = abs(spaces_to_add)
self.source[line_index] = self.source[line_index][offset:]
def fix_e201(self, result):
"""Remove extraneous whitespace."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
fixed = fix_whitespace(target,
offset=offset,
replacement='')
self.source[line_index] = fixed
def fix_e224(self, result):
"""Remove extraneous whitespace around operator."""
target = self.source[result['line'] - 1]
offset = result['column'] - 1
fixed = target[:offset] + target[offset:].replace('\t', ' ')
self.source[result['line'] - 1] = fixed
def fix_e225(self, result):
"""Fix missing whitespace around operator."""
target = self.source[result['line'] - 1]
offset = result['column'] - 1
fixed = target[:offset] + ' ' + target[offset:]
# Only proceed if non-whitespace characters match.
# And make sure we don't break the indentation.
if (
fixed.replace(' ', '') == target.replace(' ', '') and
_get_indentation(fixed) == _get_indentation(target)
):
self.source[result['line'] - 1] = fixed
error_code = result.get('id', 0)
try:
ts = generate_tokens(fixed)
except (SyntaxError, tokenize.TokenError):
return
if not check_syntax(fixed.lstrip()):
return
errors = list(
pycodestyle.missing_whitespace_around_operator(fixed, ts))
for e in reversed(errors):
if error_code != e[1].split()[0]:
continue
offset = e[0][1]
fixed = fixed[:offset] + ' ' + fixed[offset:]
self.source[result['line'] - 1] = fixed
else:
return []
def fix_e231(self, result):
"""Add missing whitespace."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column']
fixed = target[:offset].rstrip() + ' ' + target[offset:].lstrip()
self.source[line_index] = fixed
def fix_e251(self, result):
"""Remove whitespace around parameter '=' sign."""
line_index = result['line'] - 1
target = self.source[line_index]
# This is necessary since pycodestyle sometimes reports columns that
# goes past the end of the physical line. This happens in cases like,
# foo(bar\n=None)
c = min(result['column'] - 1,
len(target) - 1)
if target[c].strip():
fixed = target
else:
fixed = target[:c].rstrip() + target[c:].lstrip()
# There could be an escaped newline
#
# def foo(a=\
# 1)
if fixed.endswith(('=\\\n', '=\\\r\n', '=\\\r')):
self.source[line_index] = fixed.rstrip('\n\r \t\\')
self.source[line_index + 1] = self.source[line_index + 1].lstrip()
return [line_index + 1, line_index + 2] # Line indexed at 1
self.source[result['line'] - 1] = fixed
def fix_e262(self, result):
"""Fix spacing after inline comment hash."""
target = self.source[result['line'] - 1]
offset = result['column']
code = target[:offset].rstrip(' \t#')
comment = target[offset:].lstrip(' \t#')
fixed = code + (' # ' + comment if comment.strip() else '\n')
self.source[result['line'] - 1] = fixed
def fix_e265(self, result):
"""Fix spacing after block comment hash."""
target = self.source[result['line'] - 1]
indent = _get_indentation(target)
line = target.lstrip(' \t')
pos = next((index for index, c in enumerate(line) if c != '#'))
hashes = line[:pos]
comment = line[pos:].lstrip(' \t')
# Ignore special comments, even in the middle of the file.
if comment.startswith('!'):
return
fixed = indent + hashes + (' ' + comment if comment.strip() else '\n')
self.source[result['line'] - 1] = fixed
def fix_e266(self, result):
"""Fix too many block comment hashes."""
target = self.source[result['line'] - 1]
# Leave stylistic outlined blocks alone.
if target.strip().endswith('#'):
return
indentation = _get_indentation(target)
fixed = indentation + '# ' + target.lstrip('# \t')
self.source[result['line'] - 1] = fixed
def fix_e271(self, result):
"""Fix extraneous whitespace around keywords."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
fixed = fix_whitespace(target,
offset=offset,
replacement=' ')
if fixed == target:
return []
else:
self.source[line_index] = fixed
def fix_e301(self, result):
"""Add missing blank line."""
cr = '\n'
self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
def fix_e302(self, result):
"""Add missing 2 blank lines."""
add_linenum = 2 - int(result['info'].split()[-1])
offset = 1
if self.source[result['line'] - 2].strip() == "\\":
offset = 2
cr = '\n' * add_linenum
self.source[result['line'] - offset] = (
cr + self.source[result['line'] - offset]
)
def fix_e303(self, result):
"""Remove extra blank lines."""
delete_linenum = int(result['info'].split('(')[1].split(')')[0]) - 2
delete_linenum = max(1, delete_linenum)
# We need to count because pycodestyle reports an offset line number if
# there are comments.
cnt = 0
line = result['line'] - 2
modified_lines = []
while cnt < delete_linenum and line >= 0:
if not self.source[line].strip():
self.source[line] = ''
modified_lines.append(1 + line) # Line indexed at 1
cnt += 1
line -= 1
return modified_lines
def fix_e304(self, result):
"""Remove blank line following function decorator."""
line = result['line'] - 2
if not self.source[line].strip():
self.source[line] = ''
def fix_e305(self, result):
"""Add missing 2 blank lines after end of function or class."""
add_delete_linenum = 2 - int(result['info'].split()[-1])
cnt = 0
offset = result['line'] - 2
modified_lines = []
if add_delete_linenum < 0:
# delete cr
add_delete_linenum = abs(add_delete_linenum)
while cnt < add_delete_linenum and offset >= 0:
if not self.source[offset].strip():
self.source[offset] = ''
modified_lines.append(1 + offset) # Line indexed at 1
cnt += 1
offset -= 1
else:
# add cr
cr = '\n'
# check comment line
while True:
if offset < 0:
break
line = self.source[offset].lstrip()
if not line:
break
if line[0] != '#':
break
offset -= 1
offset += 1
self.source[offset] = cr + self.source[offset]
modified_lines.append(1 + offset) # Line indexed at 1.
return modified_lines
def fix_e401(self, result):
"""Put imports on separate lines."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
if not target.lstrip().startswith('import'):
return []
indentation = re.split(pattern=r'\bimport\b',
string=target, maxsplit=1)[0]
fixed = (target[:offset].rstrip('\t ,') + '\n' +
indentation + 'import ' + target[offset:].lstrip('\t ,'))
self.source[line_index] = fixed
def fix_e402(self, result):
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
for i in range(1, 100):
line = "".join(self.source[line_index:line_index+i])
try:
generate_tokens("".join(line))
except (SyntaxError, tokenize.TokenError):
continue
break
if not (target in self.imports and self.imports[target] != line_index):
mod_offset = get_module_imports_on_top_of_file(self.source,
line_index)
self.source[mod_offset] = line + self.source[mod_offset]
for offset in range(i):
self.source[line_index+offset] = ''
def fix_long_line_logically(self, result, logical):
"""Try to make lines fit within --max-line-length characters."""
if (
not logical or
len(logical[2]) == 1 or
self.source[result['line'] - 1].lstrip().startswith('#')
):
return self.fix_long_line_physically(result)
start_line_index = logical[0][0]
end_line_index = logical[1][0]
logical_lines = logical[2]
previous_line = get_item(self.source, start_line_index - 1, default='')
next_line = get_item(self.source, end_line_index + 1, default='')
single_line = join_logical_line(''.join(logical_lines))
try:
fixed = self.fix_long_line(
target=single_line,
previous_line=previous_line,
next_line=next_line,
original=''.join(logical_lines))
except (SyntaxError, tokenize.TokenError):
return self.fix_long_line_physically(result)
if fixed:
for line_index in range(start_line_index, end_line_index + 1):
self.source[line_index] = ''
self.source[start_line_index] = fixed
return range(start_line_index + 1, end_line_index + 1)
return []
def fix_long_line_physically(self, result):
"""Try to make lines fit within --max-line-length characters."""
line_index = result['line'] - 1
target = self.source[line_index]
previous_line = get_item(self.source, line_index - 1, default='')
next_line = get_item(self.source, line_index + 1, default='')
try:
fixed = self.fix_long_line(
target=target,
previous_line=previous_line,
next_line=next_line,
original=target)
except (SyntaxError, tokenize.TokenError):
return []
if fixed:
self.source[line_index] = fixed
return [line_index + 1]
return []
def fix_long_line(self, target, previous_line,
next_line, original):
cache_entry = (target, previous_line, next_line)
if cache_entry in self.long_line_ignore_cache:
return []
if target.lstrip().startswith('#'):
if self.options.aggressive:
# Wrap commented lines.
return shorten_comment(
line=target,
max_line_length=self.options.max_line_length,
last_comment=not next_line.lstrip().startswith('#'))
return []
fixed = get_fixed_long_line(
target=target,
previous_line=previous_line,
original=original,
indent_word=self.indent_word,
max_line_length=self.options.max_line_length,
aggressive=self.options.aggressive,
experimental=self.options.experimental,
verbose=self.options.verbose)
if fixed and not code_almost_equal(original, fixed):
return fixed
self.long_line_ignore_cache.add(cache_entry)
return None
def fix_e502(self, result):
"""Remove extraneous escape of newline."""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
self.source[line_index] = target.rstrip('\n\r \t\\') + '\n'
def fix_e701(self, result):
"""Put colon-separated compound statement on separate lines."""
line_index = result['line'] - 1
target = self.source[line_index]
c = result['column']
fixed_source = (target[:c] + '\n' +
_get_indentation(target) + self.indent_word +
target[c:].lstrip('\n\r \t\\'))
self.source[result['line'] - 1] = fixed_source
return [result['line'], result['line'] + 1]
def fix_e702(self, result, logical):
"""Put semicolon-separated compound statement on separate lines."""
if not logical:
return [] # pragma: no cover
logical_lines = logical[2]
# Avoid applying this when indented.
# https://docs.python.org/reference/compound_stmts.html
for line in logical_lines:
if (result['id'] == 'E702' and ':' in line
and STARTSWITH_INDENT_STATEMENT_REGEX.match(line)):
if self.options.verbose:
print(
'---> avoid fixing {error} with '
'other compound statements'.format(error=result['id']),
file=sys.stderr
)
return []
line_index = result['line'] - 1
target = self.source[line_index]
if target.rstrip().endswith('\\'):
# Normalize '1; \\\n2' into '1; 2'.
self.source[line_index] = target.rstrip('\n \r\t\\')
self.source[line_index + 1] = self.source[line_index + 1].lstrip()
return [line_index + 1, line_index + 2]
if target.rstrip().endswith(';'):
self.source[line_index] = target.rstrip('\n \r\t;') + '\n'
return [line_index + 1]
offset = result['column'] - 1
first = target[:offset].rstrip(';').rstrip()
second = (_get_indentation(logical_lines[0]) +
target[offset:].lstrip(';').lstrip())
# Find inline comment.
inline_comment = None
if target[offset:].lstrip(';').lstrip()[:2] == '# ':
inline_comment = target[offset:].lstrip(';')
if inline_comment:
self.source[line_index] = first + inline_comment
else:
self.source[line_index] = first + '\n' + second
return [line_index + 1]
def fix_e704(self, result):
"""Fix multiple statements on one line def"""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
match = STARTSWITH_DEF_REGEX.match(target)
if match:
self.source[line_index] = '{}\n{}{}'.format(
match.group(0),
_get_indentation(target) + self.indent_word,
target[match.end(0):].lstrip())
def fix_e711(self, result):
"""Fix comparison with None."""
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
right_offset = offset + 2
if right_offset >= len(target):
return []
left = target[:offset].rstrip()
center = target[offset:right_offset]
right = target[right_offset:].lstrip()
if center.strip() == '==':
new_center = 'is'
elif center.strip() == '!=':
new_center = 'is not'
else:
return []
self.source[line_index] = ' '.join([left, new_center, right])
def fix_e712(self, result):
"""Fix (trivial case of) comparison with boolean."""
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
# Handle very easy "not" special cases.
if re.match(r'^\s*if [\w."\'\[\]]+ == False:$', target):
self.source[line_index] = re.sub(r'if ([\w."\'\[\]]+) == False:',
r'if not \1:', target, count=1)
elif re.match(r'^\s*if [\w."\'\[\]]+ != True:$', target):
self.source[line_index] = re.sub(r'if ([\w."\'\[\]]+) != True:',
r'if not \1:', target, count=1)
else:
right_offset = offset + 2
if right_offset >= len(target):
return []
left = target[:offset].rstrip()
center = target[offset:right_offset]
right = target[right_offset:].lstrip()
# Handle simple cases only.
new_right = None
if center.strip() == '==':
if re.match(r'\bTrue\b', right):
new_right = re.sub(r'\bTrue\b *', '', right, count=1)
elif center.strip() == '!=':
if re.match(r'\bFalse\b', right):
new_right = re.sub(r'\bFalse\b *', '', right, count=1)
if new_right is None:
return []
if new_right[0].isalnum():
new_right = ' ' + new_right
self.source[line_index] = left + new_right
def fix_e713(self, result):
"""Fix (trivial case of) non-membership check."""
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
# to convert once 'not in' -> 'in'
before_target = target[:offset]
target = target[offset:]
match_notin = COMPARE_NEGATIVE_REGEX_THROUGH.search(target)
notin_pos_start, notin_pos_end = 0, 0
if match_notin:
notin_pos_start = match_notin.start(1)
notin_pos_end = match_notin.end()
target = '{}{} {}'.format(
target[:notin_pos_start], 'in', target[notin_pos_end:])
# fix 'not in'
match = COMPARE_NEGATIVE_REGEX.search(target)
if match:
if match.group(3) == 'in':
pos_start = match.start(1)
new_target = '{5}{0}{1} {2} {3} {4}'.format(
target[:pos_start], match.group(2), match.group(1),
match.group(3), target[match.end():], before_target)
if match_notin:
# revert 'in' -> 'not in'
pos_start = notin_pos_start + offset
pos_end = notin_pos_end + offset - 4 # len('not ')
new_target = '{}{} {}'.format(
new_target[:pos_start], 'not in', new_target[pos_end:])
self.source[line_index] = new_target
def fix_e714(self, result):
"""Fix object identity should be 'is not' case."""
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
# to convert once 'is not' -> 'is'
before_target = target[:offset]
target = target[offset:]
match_isnot = COMPARE_NEGATIVE_REGEX_THROUGH.search(target)
isnot_pos_start, isnot_pos_end = 0, 0
if match_isnot:
isnot_pos_start = match_isnot.start(1)
isnot_pos_end = match_isnot.end()
target = '{}{} {}'.format(
target[:isnot_pos_start], 'in', target[isnot_pos_end:])
match = COMPARE_NEGATIVE_REGEX.search(target)
if match:
if match.group(3).startswith('is'):
pos_start = match.start(1)
new_target = '{5}{0}{1} {2} {3} {4}'.format(
target[:pos_start], match.group(2), match.group(3),
match.group(1), target[match.end():], before_target)
if match_isnot:
# revert 'is' -> 'is not'
pos_start = isnot_pos_start + offset
pos_end = isnot_pos_end + offset - 4 # len('not ')
new_target = '{}{} {}'.format(
new_target[:pos_start], 'is not', new_target[pos_end:])
self.source[line_index] = new_target
def fix_e722(self, result):
"""fix bare except"""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
match = BARE_EXCEPT_REGEX.search(target)
if match:
self.source[line_index] = '{}{}{}'.format(
target[:result['column'] - 1], "except BaseException:",
target[match.end():])
def fix_e731(self, result):
"""Fix do not assign a lambda expression check."""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
match = LAMBDA_REGEX.search(target)
if match:
end = match.end()
self.source[line_index] = '{}def {}({}): return {}'.format(
target[:match.start(0)], match.group(1), match.group(2),
target[end:].lstrip())
def fix_w291(self, result):
"""Remove trailing whitespace."""
fixed_line = self.source[result['line'] - 1].rstrip()
self.source[result['line'] - 1] = fixed_line + '\n'
def fix_w391(self, _):
"""Remove trailing blank lines."""
blank_count = 0
for line in reversed(self.source):
line = line.rstrip()
if line:
break
else:
blank_count += 1
original_length = len(self.source)
self.source = self.source[:original_length - blank_count]
return range(1, 1 + original_length)
def fix_w503(self, result):
(line_index, _, target) = get_index_offset_contents(result,
self.source)
one_string_token = target.split()[0]
try:
ts = generate_tokens(one_string_token)
except (SyntaxError, tokenize.TokenError):
return
if not _is_binary_operator(ts[0][0], one_string_token):
return
# find comment
comment_index = 0
found_not_comment_only_line = False
comment_only_linenum = 0
for i in range(5):
# NOTE: try to parse code in 5 times
if (line_index - i) < 0:
break
from_index = line_index - i - 1
if from_index < 0 or len(self.source) <= from_index:
break
to_index = line_index + 1
strip_line = self.source[from_index].lstrip()
if (
not found_not_comment_only_line and
strip_line and strip_line[0] == '#'
):
comment_only_linenum += 1
continue
found_not_comment_only_line = True
try:
ts = generate_tokens("".join(self.source[from_index:to_index]))
except (SyntaxError, tokenize.TokenError):
continue
newline_count = 0
newline_index = []
for index, t in enumerate(ts):
if t[0] in (tokenize.NEWLINE, tokenize.NL):
newline_index.append(index)
newline_count += 1
if newline_count > 2:
tts = ts[newline_index[-3]:]
else:
tts = ts
old = []
for t in tts:
if t[0] in (tokenize.NEWLINE, tokenize.NL):
newline_count -= 1
if newline_count <= 1:
break
if tokenize.COMMENT == t[0] and old and old[0] != tokenize.NL:
comment_index = old[3][1]
break
old = t
break
i = target.index(one_string_token)
fix_target_line = line_index - 1 - comment_only_linenum
self.source[line_index] = '{}{}'.format(
target[:i], target[i + len(one_string_token):].lstrip())
nl = find_newline(self.source[fix_target_line:line_index])
before_line = self.source[fix_target_line]
bl = before_line.index(nl)
if comment_index:
self.source[fix_target_line] = '{} {} {}'.format(
before_line[:comment_index], one_string_token,
before_line[comment_index + 1:])
else:
if before_line[:bl].endswith("#"):
# special case
# see: https://github.com/hhatto/autopep8/issues/503
self.source[fix_target_line] = '{}{} {}'.format(
before_line[:bl-2], one_string_token, before_line[bl-2:])
else:
self.source[fix_target_line] = '{} {}{}'.format(
before_line[:bl], one_string_token, before_line[bl:])
def fix_w504(self, result):
(line_index, _, target) = get_index_offset_contents(result,
self.source)
# NOTE: is not collect pointed out in pycodestyle==2.4.0
comment_index = 0
operator_position = None # (start_position, end_position)
for i in range(1, 6):
to_index = line_index + i
try:
ts = generate_tokens("".join(self.source[line_index:to_index]))
except (SyntaxError, tokenize.TokenError):
continue
newline_count = 0
newline_index = []
for index, t in enumerate(ts):
if _is_binary_operator(t[0], t[1]):
if t[2][0] == 1 and t[3][0] == 1:
operator_position = (t[2][1], t[3][1])
elif t[0] == tokenize.NAME and t[1] in ("and", "or"):
if t[2][0] == 1 and t[3][0] == 1:
operator_position = (t[2][1], t[3][1])
elif t[0] in (tokenize.NEWLINE, tokenize.NL):
newline_index.append(index)
newline_count += 1
if newline_count > 2:
tts = ts[:newline_index[-3]]
else:
tts = ts
old = []
for t in tts:
if tokenize.COMMENT == t[0] and old:
comment_row, comment_index = old[3]
break
old = t
break
if not operator_position:
return
target_operator = target[operator_position[0]:operator_position[1]]
if comment_index and comment_row == 1:
self.source[line_index] = '{}{}'.format(
target[:operator_position[0]].rstrip(),
target[comment_index:])
else:
self.source[line_index] = '{}{}{}'.format(
target[:operator_position[0]].rstrip(),
target[operator_position[1]:].lstrip(),
target[operator_position[1]:])
next_line = self.source[line_index + 1]
next_line_indent = 0
m = re.match(r'\s*', next_line)
if m:
next_line_indent = m.span()[1]
self.source[line_index + 1] = '{}{} {}'.format(
next_line[:next_line_indent], target_operator,
next_line[next_line_indent:])
def fix_w605(self, result):
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
self.source[line_index] = '{}\\{}'.format(
target[:offset + 1], target[offset + 1:])
def reindent(source, indent_size, leave_tabs=False):
"""Reindent all lines."""
reindenter = Reindenter(source, leave_tabs)
return reindenter.run(indent_size)
def fix_2to3(source,
aggressive=True, select=None, ignore=None, filename='',
where='global', verbose=False):
"""Fix various deprecated code (via lib2to3)."""
if not aggressive:
return source
select = select or []
ignore = ignore or []
return refactor(source,
code_to_2to3(select=select,
ignore=ignore,
where=where,
verbose=verbose),
filename=filename)
def global_fixes():
"""Yield multiple (code, function) tuples."""
for function in list(globals().values()):
if inspect.isfunction(function):
arguments = _get_parameters(function)
if arguments[:1] != ['source']:
continue
code = extract_code_from_function(function)
if code:
yield (code, function)
def docstring_summary(docstring):
"""Return summary of docstring."""
return docstring.split('\n')[0] if docstring else ''
The provided code snippet includes necessary dependencies for implementing the `supported_fixes` function. Write a Python function `def supported_fixes()` to solve the following problem:
Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description.
Here is the function:
def supported_fixes():
"""Yield pep8 error codes that autopep8 fixes.
Each item we yield is a tuple of the code followed by its
description.
"""
yield ('E101', docstring_summary(reindent.__doc__))
instance = FixPEP8(filename=None, options=None, contents='')
for attribute in dir(instance):
code = re.match('fix_([ew][0-9][0-9][0-9])', attribute)
if code:
yield (
code.group(1).upper(),
re.sub(r'\s+', ' ',
docstring_summary(getattr(instance, attribute).__doc__))
)
for (code, function) in sorted(global_fixes()):
yield (code.upper() + (4 - len(code)) * ' ',
re.sub(r'\s+', ' ', docstring_summary(function.__doc__)))
for code in sorted(CODE_TO_2TO3):
yield (code.upper() + (4 - len(code)) * ' ',
re.sub(r'\s+', ' ', docstring_summary(fix_2to3.__doc__))) | Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description. |
176,999 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import codecs
import collections
import copy
import difflib
import fnmatch
import inspect
import io
import itertools
import keyword
import locale
import os
import re
import signal
import sys
import textwrap
import token
import tokenize
import warnings
import ast
from configparser import ConfigParser as SafeConfigParser, Error
import pycodestyle
from pycodestyle import STARTSWITH_INDENT_STATEMENT_REGEX
if sys.platform == 'win32': # pragma: no cover
DEFAULT_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'),
'pycodestyle')
def readlines_from_file(filename):
"""Return contents of file."""
with open_with_encoding(filename) as input_file:
return input_file.readlines()
def find_files(filenames, recursive, exclude):
"""Yield filenames."""
while filenames:
name = filenames.pop(0)
if recursive and os.path.isdir(name):
for root, directories, children in os.walk(name):
filenames += [os.path.join(root, f) for f in children
if match_file(os.path.join(root, f),
exclude)]
directories[:] = [d for d in directories
if match_file(os.path.join(root, d),
exclude)]
else:
is_exclude_match = False
for pattern in exclude:
if fnmatch.fnmatch(name, pattern):
is_exclude_match = True
break
if not is_exclude_match:
yield name
def _fix_file(parameters):
"""Helper function for optionally running fix_file() in parallel."""
if parameters[1].verbose:
print('[file:{}]'.format(parameters[0]), file=sys.stderr)
try:
return fix_file(*parameters)
except IOError as error:
print(str(error), file=sys.stderr)
raise error
The provided code snippet includes necessary dependencies for implementing the `fix_multiple_files` function. Write a Python function `def fix_multiple_files(filenames, options, output=None)` to solve the following problem:
Fix list of files. Optionally fix files recursively.
Here is the function:
def fix_multiple_files(filenames, options, output=None):
"""Fix list of files.
Optionally fix files recursively.
"""
results = []
filenames = find_files(filenames, options.recursive, options.exclude)
if options.jobs > 1:
import multiprocessing
pool = multiprocessing.Pool(options.jobs)
rets = []
for name in filenames:
ret = pool.apply_async(_fix_file, ((name, options),))
rets.append(ret)
pool.close()
pool.join()
if options.diff:
for r in rets:
sys.stdout.write(r.get().decode())
sys.stdout.flush()
results.extend([x.get() for x in rets if x is not None])
else:
for name in filenames:
ret = _fix_file((name, options, output))
if ret is None:
continue
if options.diff:
if ret != '':
results.append(ret)
elif options.in_place:
results.append(ret)
else:
original_source = readlines_from_file(name)
if "".join(original_source).splitlines() != ret.splitlines():
results.append(ret)
return results | Fix list of files. Optionally fix files recursively. |
177,000 | import imp
import os
import shutil
import stat
import sys
import traceback
import pythoncom
import win32api
import winerror
from win32com.client import Dispatch, GetObject
from win32com.client.gencache import EnsureDispatch, EnsureModule
def _AssignScriptMapsReplace(target, script_maps):
target.ScriptMaps = script_maps | null |
177,001 | import imp
import os
import shutil
import stat
import sys
import traceback
import pythoncom
import win32api
import winerror
from win32com.client import Dispatch, GetObject
from win32com.client.gencache import EnsureDispatch, EnsureModule
def get_unique_items(sequence, reference):
"Return items in sequence that can't be found in reference."
return tuple([item for item in sequence if item not in reference])
def _AssignScriptMapsEnd(target, script_maps):
unique_new_maps = get_unique_items(script_maps, target.ScriptMaps)
target.ScriptMaps = target.ScriptMaps + unique_new_maps | null |
177,002 | import imp
import os
import shutil
import stat
import sys
import traceback
import pythoncom
import win32api
import winerror
from win32com.client import Dispatch, GetObject
from win32com.client.gencache import EnsureDispatch, EnsureModule
def get_unique_items(sequence, reference):
"Return items in sequence that can't be found in reference."
return tuple([item for item in sequence if item not in reference])
def _AssignScriptMapsStart(target, script_maps):
unique_new_maps = get_unique_items(script_maps, target.ScriptMaps)
target.ScriptMaps = unique_new_maps + target.ScriptMaps | null |
177,003 | import imp
import os
import shutil
import stat
import sys
import traceback
import pythoncom
import win32api
import winerror
from win32com.client import Dispatch, GetObject
from win32com.client.gencache import EnsureDispatch, EnsureModule
class ConfigurationError(InstallationError):
pass
def Install(params, options):
_CallHook(params, "PreInstall", options)
for vd in params.VirtualDirs:
CreateDirectory(vd, options)
for filter_def in params.Filters:
CreateISAPIFilter(filter_def, options)
AddExtensionFiles(params, options)
_CallHook(params, "PostInstall", options)
def _PatchParamsModule(params, dll_name, file_must_exist=True):
if file_must_exist:
if not os.path.isfile(dll_name):
raise ConfigurationError("%s does not exist" % (dll_name,))
# Patch up all references to the DLL.
for f in params.Filters:
if f.Path is None:
f.Path = dll_name
for d in params.VirtualDirs:
for sm in d.ScriptMaps:
if sm.Module is None:
sm.Module = dll_name
def GetLoaderModuleName(mod_name, check_module=None):
# find the name of the DLL hosting us.
# By default, this is "_{module_base_name}.dll"
if hasattr(sys, "frozen"):
# What to do? The .dll knows its name, but this is likely to be
# executed via a .exe, which does not know.
base, ext = os.path.splitext(mod_name)
path, base = os.path.split(base)
# handle the common case of 'foo.exe'/'foow.exe'
if base.endswith("w"):
base = base[:-1]
# For py2exe, we have '_foo.dll' as the standard pyisapi loader - but
# 'foo.dll' is what we use (it just delegates).
# So no leading '_' on the installed name.
dll_name = os.path.abspath(os.path.join(path, base + ".dll"))
else:
base, ext = os.path.splitext(mod_name)
path, base = os.path.split(base)
dll_name = os.path.abspath(os.path.join(path, "_" + base + ".dll"))
# Check we actually have it.
if check_module is None:
check_module = not hasattr(sys, "frozen")
if check_module:
CheckLoaderModule(dll_name)
return dll_name
The provided code snippet includes necessary dependencies for implementing the `InstallModule` function. Write a Python function `def InstallModule(conf_module_name, params, options, log=lambda *args: None)` to solve the following problem:
Install the extension
Here is the function:
def InstallModule(conf_module_name, params, options, log=lambda *args: None):
"Install the extension"
if not hasattr(sys, "frozen"):
conf_module_name = os.path.abspath(conf_module_name)
if not os.path.isfile(conf_module_name):
raise ConfigurationError("%s does not exist" % (conf_module_name,))
loader_dll = GetLoaderModuleName(conf_module_name)
_PatchParamsModule(params, loader_dll)
Install(params, options)
log(1, "Installation complete.") | Install the extension |
177,004 | import imp
import os
import shutil
import stat
import sys
import traceback
import pythoncom
import win32api
import winerror
from win32com.client import Dispatch, GetObject
from win32com.client.gencache import EnsureDispatch, EnsureModule
def Uninstall(params, options):
_CallHook(params, "PreRemove", options)
DeleteExtensionFileRecords(params, options)
for vd in params.VirtualDirs:
_CallHook(vd, "PreRemove", options)
RemoveDirectory(vd, options)
if vd.is_root():
# if this is installed to the root virtual directory, we can't delete it
# so remove the script maps.
RemoveScriptMaps(vd, options)
_CallHook(vd, "PostRemove", options)
for filter_def in params.Filters:
DeleteISAPIFilter(filter_def, options)
_CallHook(params, "PostRemove", options)
def _PatchParamsModule(params, dll_name, file_must_exist=True):
if file_must_exist:
if not os.path.isfile(dll_name):
raise ConfigurationError("%s does not exist" % (dll_name,))
# Patch up all references to the DLL.
for f in params.Filters:
if f.Path is None:
f.Path = dll_name
for d in params.VirtualDirs:
for sm in d.ScriptMaps:
if sm.Module is None:
sm.Module = dll_name
def GetLoaderModuleName(mod_name, check_module=None):
# find the name of the DLL hosting us.
# By default, this is "_{module_base_name}.dll"
if hasattr(sys, "frozen"):
# What to do? The .dll knows its name, but this is likely to be
# executed via a .exe, which does not know.
base, ext = os.path.splitext(mod_name)
path, base = os.path.split(base)
# handle the common case of 'foo.exe'/'foow.exe'
if base.endswith("w"):
base = base[:-1]
# For py2exe, we have '_foo.dll' as the standard pyisapi loader - but
# 'foo.dll' is what we use (it just delegates).
# So no leading '_' on the installed name.
dll_name = os.path.abspath(os.path.join(path, base + ".dll"))
else:
base, ext = os.path.splitext(mod_name)
path, base = os.path.split(base)
dll_name = os.path.abspath(os.path.join(path, "_" + base + ".dll"))
# Check we actually have it.
if check_module is None:
check_module = not hasattr(sys, "frozen")
if check_module:
CheckLoaderModule(dll_name)
return dll_name
The provided code snippet includes necessary dependencies for implementing the `UninstallModule` function. Write a Python function `def UninstallModule(conf_module_name, params, options, log=lambda *args: None)` to solve the following problem:
Remove the extension
Here is the function:
def UninstallModule(conf_module_name, params, options, log=lambda *args: None):
"Remove the extension"
loader_dll = GetLoaderModuleName(conf_module_name, False)
_PatchParamsModule(params, loader_dll, False)
Uninstall(params, options)
log(1, "Uninstallation complete.") | Remove the extension |
177,005 | import imp
import os
import shutil
import stat
import sys
import traceback
import pythoncom
import win32api
import winerror
from win32com.client import Dispatch, GetObject
from win32com.client.gencache import EnsureDispatch, EnsureModule
_IIS_OBJECT = "IIS://LocalHost/W3SVC"
verbose = 1
def log(level, what):
if verbose >= level:
print(what)
class InstallationError(Exception):
pass
class ItemNotFound(InstallationError):
pass
standard_arguments = {
"install": InstallModule,
"remove": UninstallModule,
}
def build_usage(handler_map):
docstrings = [handler.__doc__ for handler in handler_map.values()]
all_args = dict(zip(iter(handler_map.keys()), docstrings))
arg_names = "|".join(iter(all_args.keys()))
usage_string = "%prog [options] [" + arg_names + "]\n"
usage_string += "commands:\n"
for arg, desc in all_args.items():
usage_string += " %-10s: %s" % (arg, desc) + "\n"
return usage_string[:-1]
def MergeStandardOptions(options, params):
"""
Take an options object generated by the command line and merge
the values into the IISParameters object.
"""
pass
class OptionParser(OptionContainer):
allow_interspersed_args: bool
epilog: Optional[_Text]
formatter: HelpFormatter
largs: Optional[List[_Text]]
option_groups: List[OptionParser]
option_list: List[Option]
process_default_values: Any
prog: Optional[_Text]
rargs: Optional[List[Any]]
standard_option_list: List[Option]
usage: Optional[_Text]
values: Optional[Values]
version: _Text
def __init__(
self,
usage: Optional[_Text] = ...,
option_list: Iterable[Option] = ...,
option_class: Type[Option] = ...,
version: Optional[_Text] = ...,
conflict_handler: _Text = ...,
description: Optional[_Text] = ...,
formatter: Optional[HelpFormatter] = ...,
add_help_option: bool = ...,
prog: Optional[_Text] = ...,
epilog: Optional[_Text] = ...,
) -> None: ...
def _add_help_option(self) -> None: ...
def _add_version_option(self) -> None: ...
def _create_option_list(self) -> None: ...
def _get_all_options(self) -> List[Option]: ...
def _get_args(self, args: Iterable[Any]) -> List[Any]: ...
def _init_parsing_state(self) -> None: ...
def _match_long_opt(self, opt: _Text) -> _Text: ...
def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ...
def _process_args(self, largs: List[Any], rargs: List[Any], values: Values) -> None: ...
def _process_long_opt(self, rargs: List[Any], values: Any) -> None: ...
def _process_short_opts(self, rargs: List[Any], values: Any) -> None: ...
def add_option_group(self, __opt_group: OptionGroup) -> OptionParser: ...
def add_option_group(self, *args: Any, **kwargs: Any) -> OptionParser: ...
def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ...
def disable_interspersed_args(self) -> None: ...
def enable_interspersed_args(self) -> None: ...
def error(self, msg: _Text) -> None: ...
def exit(self, status: int = ..., msg: Optional[str] = ...) -> None: ...
def expand_prog_name(self, s: Optional[_Text]) -> Any: ...
def format_epilog(self, formatter: HelpFormatter) -> Any: ...
def format_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ...
def format_option_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ...
def get_default_values(self) -> Values: ...
def get_option_group(self, opt_str: _Text) -> Any: ...
def get_prog_name(self) -> _Text: ...
def get_usage(self) -> _Text: ...
def get_version(self) -> _Text: ...
def parse_args(
self, args: Optional[Sequence[AnyStr]] = ..., values: Optional[Values] = ...
) -> Tuple[Values, List[AnyStr]]: ...
def print_usage(self, file: Optional[IO[str]] = ...) -> None: ...
def print_help(self, file: Optional[IO[str]] = ...) -> None: ...
def print_version(self, file: Optional[IO[str]] = ...) -> None: ...
def set_default(self, dest: Any, value: Any) -> None: ...
def set_defaults(self, **kwargs: Any) -> None: ...
def set_process_default_values(self, process: Any) -> None: ...
def set_usage(self, usage: _Text) -> None: ...
The provided code snippet includes necessary dependencies for implementing the `HandleCommandLine` function. Write a Python function `def HandleCommandLine( params, argv=None, conf_module_name=None, default_arg="install", opt_parser=None, custom_arg_handlers={}, )` to solve the following problem:
Perform installation or removal of an ISAPI filter or extension. This module handles standard command-line options and configuration information, and installs, removes or updates the configuration of an ISAPI filter or extension. You must pass your configuration information in params - all other arguments are optional, and allow you to configure the installation process.
Here is the function:
def HandleCommandLine(
params,
argv=None,
conf_module_name=None,
default_arg="install",
opt_parser=None,
custom_arg_handlers={},
):
"""Perform installation or removal of an ISAPI filter or extension.
This module handles standard command-line options and configuration
information, and installs, removes or updates the configuration of an
ISAPI filter or extension.
You must pass your configuration information in params - all other
arguments are optional, and allow you to configure the installation
process.
"""
global verbose
from optparse import OptionParser
argv = argv or sys.argv
if not conf_module_name:
conf_module_name = sys.argv[0]
# convert to a long name so that if we were somehow registered with
# the "short" version but unregistered with the "long" version we
# still work (that will depend on exactly how the installer was
# started)
try:
conf_module_name = win32api.GetLongPathName(conf_module_name)
except win32api.error as exc:
log(
2,
"Couldn't determine the long name for %r: %s" % (conf_module_name, exc),
)
if opt_parser is None:
# Build our own parser.
parser = OptionParser(usage="")
else:
# The caller is providing their own filter, presumably with their
# own options all setup.
parser = opt_parser
# build a usage string if we don't have one.
if not parser.get_usage():
all_handlers = standard_arguments.copy()
all_handlers.update(custom_arg_handlers)
parser.set_usage(build_usage(all_handlers))
# allow the user to use uninstall as a synonym for remove if it wasn't
# defined by the custom arg handlers.
all_handlers.setdefault("uninstall", all_handlers["remove"])
parser.add_option(
"-q",
"--quiet",
action="store_false",
dest="verbose",
default=True,
help="don't print status messages to stdout",
)
parser.add_option(
"-v",
"--verbosity",
action="count",
dest="verbose",
default=1,
help="increase the verbosity of status messages",
)
parser.add_option(
"",
"--server",
action="store",
help="Specifies the IIS server to install/uninstall on."
" Default is '%s/1'" % (_IIS_OBJECT,),
)
(options, args) = parser.parse_args(argv[1:])
MergeStandardOptions(options, params)
verbose = options.verbose
if not args:
args = [default_arg]
try:
for arg in args:
handler = all_handlers[arg]
handler(conf_module_name, params, options, log)
except (ItemNotFound, InstallationError) as details:
if options.verbose > 1:
traceback.print_exc()
print("%s: %s" % (details.__class__.__name__, details))
except KeyError:
parser.error("Invalid arg '%s'" % arg) | Perform installation or removal of an ISAPI filter or extension. This module handles standard command-line options and configuration information, and installs, removes or updates the configuration of an ISAPI filter or extension. You must pass your configuration information in params - all other arguments are optional, and allow you to configure the installation process. |
177,006 | import sys
import urllib.error
import urllib.parse
import urllib.request
from isapi import isapicon, threaded_extension
CHUNK_SIZE = 8192
def io_callback(ecb, fp, cbIO, errcode):
print("IO callback", ecb, fp, cbIO, errcode)
chunk = fp.read(CHUNK_SIZE)
if chunk:
ecb.WriteClient(chunk, isapicon.HSE_IO_ASYNC)
# and wait for the next callback to say this chunk is done.
else:
# eof - say we are complete.
fp.close()
ecb.DoneWithSession() | null |
177,007 | import sys
import urllib.error
import urllib.parse
import urllib.request
from isapi import isapicon, threaded_extension
class Extension(threaded_extension.ThreadPoolExtension):
"Python sample proxy server - asynch version."
def Dispatch(self, ecb):
print('IIS dispatching "%s"' % (ecb.GetServerVariable("URL"),))
url = ecb.GetServerVariable("URL")
new_url = proxy + url
print("Opening %s" % new_url)
fp = urllib.request.urlopen(new_url)
headers = fp.info()
ecb.SendResponseHeaders("200 OK", str(headers) + "\r\n", False)
# now send the first chunk asynchronously
ecb.ReqIOCompletion(io_callback, fp)
chunk = fp.read(CHUNK_SIZE)
if chunk:
ecb.WriteClient(chunk, isapicon.HSE_IO_ASYNC)
return isapicon.HSE_STATUS_PENDING
# no data - just close things now.
ecb.DoneWithSession()
return isapicon.HSE_STATUS_SUCCESS
def __ExtensionFactory__():
return Extension() | null |
177,008 | import sys
from isapi import isapicon, threaded_extension
import win32api
def io_callback(ecb, url, cbIO, errcode):
# Get the status of our ExecURL
httpstatus, substatus, win32 = ecb.GetExecURLStatus()
print(
"ExecURL of %r finished with http status %d.%d, win32 status %d (%s)"
% (url, httpstatus, substatus, win32, win32api.FormatMessage(win32).strip())
)
# nothing more to do!
ecb.DoneWithSession() | null |
177,009 | import sys
from isapi import isapicon, threaded_extension
import win32api
class Extension(threaded_extension.ThreadPoolExtension):
"Python sample Extension"
def Dispatch(self, ecb):
# Note that our ThreadPoolExtension base class will catch exceptions
# in our Dispatch method, and write the traceback to the client.
# That is perfect for this sample, so we don't catch our own.
# print 'IIS dispatching "%s"' % (ecb.GetServerVariable("URL"),)
url = ecb.GetServerVariable("URL").decode("ascii")
for exclude in excludes:
if url.lower().startswith(exclude):
print("excluding %s" % url)
if ecb.Version < 0x60000:
print("(but this is IIS5 or earlier - can't do 'excludes')")
else:
ecb.IOCompletion(io_callback, url)
ecb.ExecURL(
None,
None,
None,
None,
None,
isapicon.HSE_EXEC_URL_IGNORE_CURRENT_INTERCEPTOR,
)
return isapicon.HSE_STATUS_PENDING
new_url = proxy + url
print("Opening %s" % new_url)
fp = urlopen(new_url)
headers = fp.info()
# subtle py3k breakage: in py3k, str(headers) has normalized \r\n
# back to \n and also stuck an extra \n term. py2k leaves the
# \r\n from the server in tact and finishes with a single term.
if sys.version_info < (3, 0):
header_text = str(headers) + "\r\n"
else:
# take *all* trailing \n off, replace remaining with
# \r\n, then add the 2 trailing \r\n.
header_text = str(headers).rstrip("\n").replace("\n", "\r\n") + "\r\n\r\n"
ecb.SendResponseHeaders("200 OK", header_text, False)
ecb.WriteClient(fp.read())
ecb.DoneWithSession()
print("Returned data from '%s'" % (new_url,))
return isapicon.HSE_STATUS_SUCCESS
def __ExtensionFactory__():
return Extension() | null |
177,010 | import sys
import urllib.error
import urllib.parse
import urllib.request
from isapi import isapicon, threaded_extension
from isapi.simple import SimpleFilter
class Filter(SimpleFilter):
"Sample Python Redirector"
filter_flags = isapicon.SF_NOTIFY_PREPROC_HEADERS | isapicon.SF_NOTIFY_ORDER_DEFAULT
def HttpFilterProc(self, fc):
# print "Filter Dispatch"
nt = fc.NotificationType
if nt != isapicon.SF_NOTIFY_PREPROC_HEADERS:
return isapicon.SF_STATUS_REQ_NEXT_NOTIFICATION
pp = fc.GetData()
url = pp.GetHeader("url")
# print "URL is '%s'" % (url,)
prefix = virtualdir
if not url.startswith(prefix):
new_url = prefix + url
print("New proxied URL is '%s'" % (new_url,))
pp.SetHeader("url", new_url)
# For the sake of demonstration, show how the FilterContext
# attribute is used. It always starts out life as None, and
# any assignments made are automatically decref'd by the
# framework during a SF_NOTIFY_END_OF_NET_SESSION notification.
if fc.FilterContext is None:
fc.FilterContext = 0
fc.FilterContext += 1
print("This is request number %d on this connection" % fc.FilterContext)
return isapicon.SF_STATUS_REQ_HANDLED_NOTIFICATION
else:
print("Filter ignoring URL '%s'" % (url,))
# Some older code that handled SF_NOTIFY_URL_MAP.
# ~ print "Have URL_MAP notify"
# ~ urlmap = fc.GetData()
# ~ print "URI is", urlmap.URL
# ~ print "Path is", urlmap.PhysicalPath
# ~ if urlmap.URL.startswith("/UC/"):
# ~ # Find the /UC/ in the physical path, and nuke it (except
# ~ # as the path is physical, it is \)
# ~ p = urlmap.PhysicalPath
# ~ pos = p.index("\\UC\\")
# ~ p = p[:pos] + p[pos+3:]
# ~ p = r"E:\src\pyisapi\webroot\PyTest\formTest.htm"
# ~ print "New path is", p
# ~ urlmap.PhysicalPath = p
def __FilterFactory__():
return Filter() | null |
177,011 | import sys
import urllib.error
import urllib.parse
import urllib.request
from isapi import isapicon, threaded_extension
from isapi.simple import SimpleFilter
class Extension(threaded_extension.ThreadPoolExtension):
"Python sample Extension"
def Dispatch(self, ecb):
# Note that our ThreadPoolExtension base class will catch exceptions
# in our Dispatch method, and write the traceback to the client.
# That is perfect for this sample, so we don't catch our own.
# print 'IIS dispatching "%s"' % (ecb.GetServerVariable("URL"),)
url = ecb.GetServerVariable("URL")
if url.startswith(virtualdir):
new_url = proxy + url[len(virtualdir) :]
print("Opening", new_url)
fp = urllib.request.urlopen(new_url)
headers = fp.info()
ecb.SendResponseHeaders("200 OK", str(headers) + "\r\n", False)
ecb.WriteClient(fp.read())
ecb.DoneWithSession()
print("Returned data from '%s'!" % (new_url,))
else:
# this should never happen - we should only see requests that
# start with our virtual directory name.
print("Not proxying '%s'" % (url,))
def __ExtensionFactory__():
return Extension() | null |
177,012 | import os
import stat
import sys
from isapi import isapicon
from isapi.simple import SimpleExtension
import threading
import win32con
import win32event
import win32file
import winerror
from isapi import InternalReloadException
class Extension(SimpleExtension):
"Python advanced sample Extension"
def __init__(self):
self.reload_watcher = ReloadWatcherThread()
self.reload_watcher.start()
def HttpExtensionProc(self, ecb):
# NOTE: If you use a ThreadPoolExtension, you must still perform
# this check in HttpExtensionProc - raising the exception from
# The "Dispatch" method will just cause the exception to be
# rendered to the browser.
if self.reload_watcher.change_detected:
print("Doing reload")
raise InternalReloadException
url = ecb.GetServerVariable("UNICODE_URL")
if url.endswith("ReportUnhealthy"):
ecb.ReportUnhealthy("I'm a little sick")
ecb.SendResponseHeaders("200 OK", "Content-Type: text/html\r\n\r\n", 0)
print("<HTML><BODY>", file=ecb)
qs = ecb.GetServerVariable("QUERY_STRING")
if qs:
queries = qs.split("&")
print("<PRE>", file=ecb)
for q in queries:
val = ecb.GetServerVariable(q, "<no such variable>")
print("%s=%r" % (q, val), file=ecb)
print("</PRE><P/>", file=ecb)
print("This module has been imported", file=ecb)
print("%d times" % (reload_counter,), file=ecb)
print("</BODY></HTML>", file=ecb)
ecb.close()
return isapicon.HSE_STATUS_SUCCESS
def TerminateExtension(self, status):
self.reload_watcher.stop()
def __ExtensionFactory__():
return Extension() | null |
177,013 | import os
import stat
import sys
from isapi import isapicon
from isapi.simple import SimpleExtension
import threading
import win32con
import win32event
import win32file
import winerror
from isapi import InternalReloadException
def PreInstallDirectory(params, options):
# If the user used our special '--description' option,
# then we override our default.
if options.description:
params.Description = options.description | null |
177,014 | import os
import stat
import sys
from isapi import isapicon
from isapi.simple import SimpleExtension
import threading
import win32con
import win32event
import win32file
import winerror
from isapi import InternalReloadException
def PostInstall(params, options):
print()
print("The sample has been installed.")
print("Point your browser to /AdvancedPythonSample")
print("If you modify the source file and reload the page,")
print("you should see the reload counter increment") | null |
177,015 | import os
import stat
import sys
from isapi import isapicon
from isapi.simple import SimpleExtension
import threading
import win32con
import win32event
import win32file
import winerror
from isapi import InternalReloadException
The provided code snippet includes necessary dependencies for implementing the `status_handler` function. Write a Python function `def status_handler(options, log, arg)` to solve the following problem:
Query the status of something
Here is the function:
def status_handler(options, log, arg):
"Query the status of something"
print("Everything seems to be fine!") | Query the status of something |
177,016 | import ast
import html
import os
import sys
from collections import defaultdict, Counter
from enum import Enum
from textwrap import dedent
from types import FrameType, CodeType, TracebackType
from typing import (
Iterator, List, Tuple, Optional, NamedTuple,
Any, Iterable, Callable, Union,
Sequence)
from typing import Mapping
import executing
from asttokens.util import Token
from executing import only
from pure_eval import Evaluator, is_expression_interesting
from stack_data.utils import (
truncate, unique_in_order, line_range,
frame_and_lineno, iter_stack, collapse_repeated, group_by_key_func,
cached_property, is_frame, _pygmented_with_ranges, assert_)
RangeInLine = NamedTuple('RangeInLine',
[('start', int),
('end', int),
('data', Any)])
RangeInLine.__doc__ = """
Represents a range of characters within one line of source code,
and some associated data.
Typically this will be converted to a pair of markers by markers_from_ranges.
"""
MarkerInLine = NamedTuple('MarkerInLine',
[('position', int),
('is_start', bool),
('string', str)])
MarkerInLine.__doc__ = """
A string that is meant to be inserted at a given position in a line of source code.
For example, this could be an ANSI code or the opening or closing of an HTML tag.
is_start should be True if this is the first of a pair such as the opening of an HTML tag.
This will help to sort and insert markers correctly.
Typically this would be created from a RangeInLine by markers_from_ranges.
Then use Line.render to insert the markers correctly.
"""
Optional: _SpecialForm = ...
List = _Alias()
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]: ...
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
# To specify a variable-length tuple of homogeneous type, Tuple[T, ...]
# is used.
return self._generics_manager.is_homogenous_tuple()
def py__simple_getitem__(self, index):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
else:
if isinstance(index, int):
return self._generics_manager.get_index_and_execute(index)
debug.dbg('The getitem type on Tuple was %s' % index)
return NO_VALUES
def py__iter__(self, contextualized_node=None):
if self._is_homogenous():
yield LazyKnownValues(self._generics_manager.get_index_and_execute(0))
else:
for v in self._generics_manager.to_tuple():
yield LazyKnownValues(v.execute_annotation())
def py__getitem__(self, index_value_set, contextualized_node):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
return ValueSet.from_sets(
self._generics_manager.to_tuple()
).execute_annotation()
def _get_wrapped_value(self):
tuple_, = self.inference_state.builtins_module \
.py__getattribute__('tuple').execute_annotation()
return tuple_
def name(self):
return self._wrapped_value.name
def infer_type_vars(self, value_set):
# Circular
from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts
value_set = value_set.filter(
lambda x: x.py__name__().lower() == 'tuple',
)
if self._is_homogenous():
# The parameter annotation is of the form `Tuple[T, ...]`,
# so we treat the incoming tuple like a iterable sequence
# rather than a positional container of elements.
return self._class_value.get_generics()[0].infer_type_vars(
value_set.merge_types_of_iterate(),
)
else:
# The parameter annotation has only explicit type parameters
# (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we
# treat the incoming values as needing to match the annotation
# exactly, just as we would for non-tuple annotations.
type_var_dict = {}
for element in value_set:
try:
method = element.get_annotated_class_object
except AttributeError:
# This might still happen, because the tuple name matching
# above is not 100% correct, so just catch the remaining
# cases here.
continue
py_class = method()
merge_type_var_dicts(
type_var_dict,
merge_pairwise_generics(self._class_value, py_class),
)
return type_var_dict
The provided code snippet includes necessary dependencies for implementing the `markers_from_ranges` function. Write a Python function `def markers_from_ranges( ranges: Iterable[RangeInLine], converter: Callable[[RangeInLine], Optional[Tuple[str, str]]], ) -> List[MarkerInLine]` to solve the following problem:
Helper to create MarkerInLines given some RangeInLines. converter should be a function accepting a RangeInLine returning either None (which is ignored) or a pair of strings which are used to create two markers included in the returned list.
Here is the function:
def markers_from_ranges(
ranges: Iterable[RangeInLine],
converter: Callable[[RangeInLine], Optional[Tuple[str, str]]],
) -> List[MarkerInLine]:
"""
Helper to create MarkerInLines given some RangeInLines.
converter should be a function accepting a RangeInLine returning
either None (which is ignored) or a pair of strings which
are used to create two markers included in the returned list.
"""
markers = []
for rang in ranges:
converted = converter(rang)
if converted is None:
continue
start_string, end_string = converted
if not (isinstance(start_string, str) and isinstance(end_string, str)):
raise TypeError("converter should return None or a pair of strings")
markers += [
MarkerInLine(position=rang.start, is_start=True, string=start_string),
MarkerInLine(position=rang.end, is_start=False, string=end_string),
]
return markers | Helper to create MarkerInLines given some RangeInLines. converter should be a function accepting a RangeInLine returning either None (which is ignored) or a pair of strings which are used to create two markers included in the returned list. |
177,017 | import ast
import html
import os
import sys
from collections import defaultdict, Counter
from enum import Enum
from textwrap import dedent
from types import FrameType, CodeType, TracebackType
from typing import (
Iterator, List, Tuple, Optional, NamedTuple,
Any, Iterable, Callable, Union,
Sequence)
from typing import Mapping
import executing
from asttokens.util import Token
from executing import only
from pure_eval import Evaluator, is_expression_interesting
from stack_data.utils import (
truncate, unique_in_order, line_range,
frame_and_lineno, iter_stack, collapse_repeated, group_by_key_func,
cached_property, is_frame, _pygmented_with_ranges, assert_)
def get_style_by_name(name):
if name in STYLE_MAP:
mod, cls = STYLE_MAP[name].split('::')
builtin = "yes"
else:
for found_name, style in find_plugin_styles():
if name == found_name:
return style
# perhaps it got dropped into our styles package
builtin = ""
mod = name
cls = name.title() + "Style"
try:
mod = __import__('pygments.styles.' + mod, None, None, [cls])
except ImportError:
raise ClassNotFound("Could not find style module %r" % mod +
(builtin and ", though it should be builtin") + ".")
try:
return getattr(mod, cls)
except AttributeError:
raise ClassNotFound("Could not find style class %r in style module." % cls)
def style_with_executing_node(style, modifier):
from pygments.styles import get_style_by_name
if isinstance(style, str):
style = get_style_by_name(style)
class NewStyle(style):
for_executing_node = True
styles = {
**style.styles,
**{
k.ExecutingNode: v + " " + modifier
for k, v in style.styles.items()
}
}
return NewStyle | null |
177,018 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
def truncate(seq, max_length: int, middle):
if len(seq) > max_length:
right = (max_length - len(middle)) // 2
left = max_length - len(middle) - right
seq = seq[:left] + middle + seq[-right:]
return seq | null |
177,019 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
T = TypeVar('T')
class OrderedDict(dict):
def __init__(self, data=None, **kwargs):
def __delitem__(self, key):
def __getitem__(self, key):
def __iter__(self):
def __missing__(self, key):
def __setitem__(self, key, item):
def clear(self):
def copy(self):
def items(self):
def keys(self, data=None, keys=None):
def popitem(self):
def setdefault(self, key, failobj=None):
def update(self, data):
def values(self):
List = _Alias()
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]:
def unique_in_order(it: Iterable[T]) -> List[T]:
return list(OrderedDict.fromkeys(it)) | null |
177,020 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
# To specify a variable-length tuple of homogeneous type, Tuple[T, ...]
# is used.
return self._generics_manager.is_homogenous_tuple()
def py__simple_getitem__(self, index):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
else:
if isinstance(index, int):
return self._generics_manager.get_index_and_execute(index)
debug.dbg('The getitem type on Tuple was %s' % index)
return NO_VALUES
def py__iter__(self, contextualized_node=None):
if self._is_homogenous():
yield LazyKnownValues(self._generics_manager.get_index_and_execute(0))
else:
for v in self._generics_manager.to_tuple():
yield LazyKnownValues(v.execute_annotation())
def py__getitem__(self, index_value_set, contextualized_node):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
return ValueSet.from_sets(
self._generics_manager.to_tuple()
).execute_annotation()
def _get_wrapped_value(self):
tuple_, = self.inference_state.builtins_module \
.py__getattribute__('tuple').execute_annotation()
return tuple_
def name(self):
return self._wrapped_value.name
def infer_type_vars(self, value_set):
# Circular
from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts
value_set = value_set.filter(
lambda x: x.py__name__().lower() == 'tuple',
)
if self._is_homogenous():
# The parameter annotation is of the form `Tuple[T, ...]`,
# so we treat the incoming tuple like a iterable sequence
# rather than a positional container of elements.
return self._class_value.get_generics()[0].infer_type_vars(
value_set.merge_types_of_iterate(),
)
else:
# The parameter annotation has only explicit type parameters
# (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we
# treat the incoming values as needing to match the annotation
# exactly, just as we would for non-tuple annotations.
type_var_dict = {}
for element in value_set:
try:
method = element.get_annotated_class_object
except AttributeError:
# This might still happen, because the tuple name matching
# above is not 100% correct, so just catch the remaining
# cases here.
continue
py_class = method()
merge_type_var_dicts(
type_var_dict,
merge_pairwise_generics(self._class_value, py_class),
)
return type_var_dict
The provided code snippet includes necessary dependencies for implementing the `line_range` function. Write a Python function `def line_range(atok: ASTText, node: ast.AST) -> Tuple[int, int]` to solve the following problem:
Returns a pair of numbers representing a half open range (i.e. suitable as arguments to the `range()` builtin) of line numbers of the given AST nodes.
Here is the function:
def line_range(atok: ASTText, node: ast.AST) -> Tuple[int, int]:
"""
Returns a pair of numbers representing a half open range
(i.e. suitable as arguments to the `range()` builtin)
of line numbers of the given AST nodes.
"""
if isinstance(node, getattr(ast, "match_case", ())):
start, _end = line_range(atok, node.pattern)
_start, end = line_range(atok, node.body[-1])
return start, end
else:
(start, _), (end, _) = atok.get_text_positions(node, padded=False)
return start, end + 1 | Returns a pair of numbers representing a half open range (i.e. suitable as arguments to the `range()` builtin) of line numbers of the given AST nodes. |
177,021 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
def highlight_unique(lst: List[T]) -> Iterator[Tuple[T, bool]]:
counts = Counter(lst)
for is_common, group in itertools.groupby(lst, key=lambda x: counts[x] > 3):
if is_common:
group = list(group)
highlighted = [False] * len(group)
def highlight_index(f):
try:
i = f()
except ValueError:
return None
highlighted[i] = True
return i
for item in set(group):
first = highlight_index(lambda: group.index(item))
if first is not None:
highlight_index(lambda: group.index(item, first + 1))
highlight_index(lambda: -1 - group[::-1].index(item))
else:
highlighted = itertools.repeat(True)
yield from zip(group, highlighted)
def identity(x: T) -> T:
return x
def collapse_repeated(lst, *, collapser, mapper=identity, key=identity):
keyed = list(map(key, lst))
for is_highlighted, group in itertools.groupby(
zip(lst, highlight_unique(keyed)),
key=lambda t: t[1][1],
):
original_group, highlighted_group = zip(*group)
if is_highlighted:
yield from map(mapper, original_group)
else:
keyed_group, _ = zip(*highlighted_group)
yield collapser(list(original_group), list(keyed_group)) | null |
177,022 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
def is_frame(frame_or_tb: Union[FrameType, TracebackType]) -> bool:
assert_(isinstance(frame_or_tb, (types.FrameType, types.TracebackType)))
return isinstance(frame_or_tb, (types.FrameType,))
class TracebackType:
if sys.version_info >= (3, 7):
def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ...
tb_next: Optional[TracebackType]
else:
def tb_next(self) -> Optional[TracebackType]: ...
# the rest are read-only even in 3.7
def tb_frame(self) -> FrameType: ...
def tb_lasti(self) -> int: ...
def tb_lineno(self) -> int: ...
class FrameType:
f_back: Optional[FrameType]
f_builtins: Dict[str, Any]
f_code: CodeType
f_globals: Dict[str, Any]
f_lasti: int
f_lineno: int
f_locals: Dict[str, Any]
f_trace: Optional[Callable[[FrameType, str, Any], Any]]
if sys.version_info >= (3, 7):
f_trace_lines: bool
f_trace_opcodes: bool
def clear(self) -> None: ...
Union: _SpecialForm = ...
class Iterator(Iterable[_T_co], Protocol[_T_co]):
def __next__(self) -> _T_co: ...
def __iter__(self) -> Iterator[_T_co]: ...
def iter_stack(frame_or_tb: Union[FrameType, TracebackType]) -> Iterator[Union[FrameType, TracebackType]]:
while frame_or_tb:
yield frame_or_tb
if is_frame(frame_or_tb):
frame_or_tb = frame_or_tb.f_back
else:
frame_or_tb = frame_or_tb.tb_next | null |
177,023 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
def is_frame(frame_or_tb: Union[FrameType, TracebackType]) -> bool:
assert_(isinstance(frame_or_tb, (types.FrameType, types.TracebackType)))
return isinstance(frame_or_tb, (types.FrameType,))
class TracebackType:
if sys.version_info >= (3, 7):
def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ...
tb_next: Optional[TracebackType]
else:
def tb_next(self) -> Optional[TracebackType]: ...
# the rest are read-only even in 3.7
def tb_frame(self) -> FrameType: ...
def tb_lasti(self) -> int: ...
def tb_lineno(self) -> int: ...
class FrameType:
f_back: Optional[FrameType]
f_builtins: Dict[str, Any]
f_code: CodeType
f_globals: Dict[str, Any]
f_lasti: int
f_lineno: int
f_locals: Dict[str, Any]
f_trace: Optional[Callable[[FrameType, str, Any], Any]]
if sys.version_info >= (3, 7):
f_trace_lines: bool
f_trace_opcodes: bool
def clear(self) -> None: ...
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
# To specify a variable-length tuple of homogeneous type, Tuple[T, ...]
# is used.
return self._generics_manager.is_homogenous_tuple()
def py__simple_getitem__(self, index):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
else:
if isinstance(index, int):
return self._generics_manager.get_index_and_execute(index)
debug.dbg('The getitem type on Tuple was %s' % index)
return NO_VALUES
def py__iter__(self, contextualized_node=None):
if self._is_homogenous():
yield LazyKnownValues(self._generics_manager.get_index_and_execute(0))
else:
for v in self._generics_manager.to_tuple():
yield LazyKnownValues(v.execute_annotation())
def py__getitem__(self, index_value_set, contextualized_node):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
return ValueSet.from_sets(
self._generics_manager.to_tuple()
).execute_annotation()
def _get_wrapped_value(self):
tuple_, = self.inference_state.builtins_module \
.py__getattribute__('tuple').execute_annotation()
return tuple_
def name(self):
return self._wrapped_value.name
def infer_type_vars(self, value_set):
# Circular
from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts
value_set = value_set.filter(
lambda x: x.py__name__().lower() == 'tuple',
)
if self._is_homogenous():
# The parameter annotation is of the form `Tuple[T, ...]`,
# so we treat the incoming tuple like a iterable sequence
# rather than a positional container of elements.
return self._class_value.get_generics()[0].infer_type_vars(
value_set.merge_types_of_iterate(),
)
else:
# The parameter annotation has only explicit type parameters
# (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we
# treat the incoming values as needing to match the annotation
# exactly, just as we would for non-tuple annotations.
type_var_dict = {}
for element in value_set:
try:
method = element.get_annotated_class_object
except AttributeError:
# This might still happen, because the tuple name matching
# above is not 100% correct, so just catch the remaining
# cases here.
continue
py_class = method()
merge_type_var_dicts(
type_var_dict,
merge_pairwise_generics(self._class_value, py_class),
)
return type_var_dict
Union: _SpecialForm = ...
def frame_and_lineno(frame_or_tb: Union[FrameType, TracebackType]) -> Tuple[FrameType, int]:
if is_frame(frame_or_tb):
return frame_or_tb, frame_or_tb.f_lineno
else:
return frame_or_tb.tb_frame, frame_or_tb.tb_lineno | null |
177,024 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
T = TypeVar('T')
R = TypeVar('R')
class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]):
default_factory: Callable[[], _VT]
def __init__(self, **kwargs: _VT) -> None: ...
def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ...
def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ...
def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ...
def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ...
def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ...
def __init__(
self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT
) -> None: ...
def __missing__(self, key: _KT) -> _VT: ...
def copy(self: _S) -> _S: ...
List = _Alias()
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]: ...
class Mapping(_Collection[_KT], Generic[_KT, _VT_co]):
# TODO: We wish the key type could also be covariant, but that doesn't work,
# see discussion in https: //github.com/python/typing/pull/273.
def __getitem__(self, k: _KT) -> _VT_co: ...
# Mixin methods
def get(self, key: _KT) -> Optional[_VT_co]: ...
def get(self, key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ...
def items(self) -> AbstractSet[Tuple[_KT, _VT_co]]: ...
def keys(self) -> AbstractSet[_KT]: ...
def values(self) -> ValuesView[_VT_co]: ...
def __contains__(self, o: object) -> bool: ...
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
The provided code snippet includes necessary dependencies for implementing the `group_by_key_func` function. Write a Python function `def group_by_key_func(iterable: Iterable[T], key_func: Callable[[T], R]) -> Mapping[R, List[T]]` to solve the following problem:
Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements of the iterable and the values are lists of elements all of which correspond to the key. >>> def si(d): return sorted(d.items()) >>> si(group_by_key_func("a bb ccc d ee fff".split(), len)) [(1, ['a', 'd']), (2, ['bb', 'ee']), (3, ['ccc', 'fff'])] >>> si(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2)) [(0, [0, 6, 8, 2]), (1, [-1, 1, 3, 9])]
Here is the function:
def group_by_key_func(iterable: Iterable[T], key_func: Callable[[T], R]) -> Mapping[R, List[T]]:
# noinspection PyUnresolvedReferences
"""
Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
of the iterable and the values are lists of elements all of which correspond to the key.
>>> def si(d): return sorted(d.items())
>>> si(group_by_key_func("a bb ccc d ee fff".split(), len))
[(1, ['a', 'd']), (2, ['bb', 'ee']), (3, ['ccc', 'fff'])]
>>> si(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2))
[(0, [0, 6, 8, 2]), (1, [-1, 1, 3, 9])]
"""
result = defaultdict(list)
for item in iterable:
result[key_func(item)].append(item)
return result | Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements of the iterable and the values are lists of elements all of which correspond to the key. >>> def si(d): return sorted(d.items()) >>> si(group_by_key_func("a bb ccc d ee fff".split(), len)) [(1, ['a', 'd']), (2, ['bb', 'ee']), (3, ['ccc', 'fff'])] >>> si(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2)) [(0, [0, 6, 8, 2]), (1, [-1, 1, 3, 9])] |
177,025 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
def get_lexer_by_name(_alias, **options):
"""Get a lexer by an alias.
Raises ClassNotFound if not found.
"""
if not _alias:
raise ClassNotFound('no lexer for alias %r found' % _alias)
# lookup builtin lexers
for module_name, name, aliases, _, _ in LEXERS.values():
if _alias.lower() in aliases:
if name not in _lexer_cache:
_load_lexers(module_name)
return _lexer_cache[name](**options)
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if _alias.lower() in cls.aliases:
return cls(**options)
raise ClassNotFound('no lexer for alias %r found' % _alias)
def _pygmented_with_ranges(formatter, code, ranges):
import pygments
from pygments.lexers import get_lexer_by_name
class MyLexer(type(get_lexer_by_name("python3"))):
def get_tokens(self, text):
length = 0
for ttype, value in super().get_tokens(text):
if any(start <= length < end for start, end in ranges):
ttype = ttype.ExecutingNode
length += len(value)
yield ttype, value
lexer = MyLexer(stripnl=False)
try:
highlighted = pygments.highlight(code, lexer, formatter)
except Exception:
# When pygments fails, prefer code without highlighting over crashing
highlighted = code
return highlighted.splitlines() | null |
177,026 | import ast
import itertools
import types
from collections import OrderedDict, Counter, defaultdict
from types import FrameType, TracebackType
from typing import (
Iterator, List, Tuple, Iterable, Callable, Union,
TypeVar, Mapping,
)
from asttokens import ASTText
def some_str(value):
try:
return str(value)
except:
return '<unprintable %s object>' % type(value).__name__ | null |
177,027 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
ERRORCODE_REGEX = re.compile(r'\b[A-Z]\d{3}\b')
_checks = {'physical_line': {}, 'logical_line': {}, 'tree': {}}
def _get_parameters(function):
return [parameter.name
for parameter
in inspect.signature(function).parameters.values()
if parameter.kind == parameter.POSITIONAL_OR_KEYWORD]
The provided code snippet includes necessary dependencies for implementing the `register_check` function. Write a Python function `def register_check(check, codes=None)` to solve the following problem:
Register a new check object.
Here is the function:
def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
args = _get_parameters(check)
if args and args[0] in ('physical_line', 'logical_line'):
if codes is None:
codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
_add_check(check, args[0], codes, args)
elif inspect.isclass(check):
if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
_add_check(check, 'tree', codes, None)
return check | Register a new check object. |
177,028 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
INDENT_REGEX = re.compile(r'([ \t]*)')
The provided code snippet includes necessary dependencies for implementing the `tabs_or_spaces` function. Write a Python function `def tabs_or_spaces(physical_line, indent_char)` to solve the following problem:
r"""Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended! Okay: if a == 0:\n a = 1\n b = 1 E101: if a == 0:\n a = 1\n\tb = 1
Here is the function:
def tabs_or_spaces(physical_line, indent_char):
r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a
mixture of tabs and spaces should be converted to using spaces
exclusively. When invoking the Python command line interpreter with
the -t option, it issues warnings about code that illegally mixes
tabs and spaces. When using -tt these warnings become errors.
These options are highly recommended!
Okay: if a == 0:\n a = 1\n b = 1
E101: if a == 0:\n a = 1\n\tb = 1
"""
indent = INDENT_REGEX.match(physical_line).group(1)
for offset, char in enumerate(indent):
if char != indent_char:
return offset, "E101 indentation contains mixed spaces and tabs" | r"""Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended! Okay: if a == 0:\n a = 1\n b = 1 E101: if a == 0:\n a = 1\n\tb = 1 |
177,029 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
INDENT_REGEX = re.compile(r'([ \t]*)')
The provided code snippet includes necessary dependencies for implementing the `tabs_obsolete` function. Write a Python function `def tabs_obsolete(physical_line)` to solve the following problem:
r"""On new projects, spaces-only are strongly recommended over tabs. Okay: if True:\n return W191: if True:\n\treturn
Here is the function:
def tabs_obsolete(physical_line):
r"""On new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn
"""
indent = INDENT_REGEX.match(physical_line).group(1)
if '\t' in indent:
return indent.index('\t'), "W191 indentation contains tabs" | r"""On new projects, spaces-only are strongly recommended over tabs. Okay: if True:\n return W191: if True:\n\treturn |
177,030 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `trailing_whitespace` function. Write a Python function `def trailing_whitespace(physical_line)` to solve the following problem:
r"""Trailing whitespace is superfluous. The warning returned varies on whether the line itself is blank, for easier filtering for those who want to indent their blank lines. Okay: spam(1)\n# W291: spam(1) \n# W293: class Foo(object):\n \n bang = 12
Here is the function:
def trailing_whitespace(physical_line):
r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
"""
physical_line = physical_line.rstrip('\n') # chr(10), newline
physical_line = physical_line.rstrip('\r') # chr(13), carriage return
physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
stripped = physical_line.rstrip(' \t\v')
if physical_line != stripped:
if stripped:
return len(stripped), "W291 trailing whitespace"
else:
return 0, "W293 blank line contains whitespace" | r"""Trailing whitespace is superfluous. The warning returned varies on whether the line itself is blank, for easier filtering for those who want to indent their blank lines. Okay: spam(1)\n# W291: spam(1) \n# W293: class Foo(object):\n \n bang = 12 |
177,031 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `trailing_blank_lines` function. Write a Python function `def trailing_blank_lines(physical_line, lines, line_number, total_lines)` to solve the following problem:
r"""Trailing blank lines are superfluous. Okay: spam(1) W391: spam(1)\n However the last line should end with a new line (warning W292).
Here is the function:
def trailing_blank_lines(physical_line, lines, line_number, total_lines):
r"""Trailing blank lines are superfluous.
Okay: spam(1)
W391: spam(1)\n
However the last line should end with a new line (warning W292).
"""
if line_number == total_lines:
stripped_last_line = physical_line.rstrip('\r\n')
if physical_line and not stripped_last_line:
return 0, "W391 blank line at end of file"
if stripped_last_line == physical_line:
return len(lines[-1]), "W292 no newline at end of file" | r"""Trailing blank lines are superfluous. Okay: spam(1) W391: spam(1)\n However the last line should end with a new line (warning W292). |
177,032 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `maximum_line_length` function. Write a Python function `def maximum_line_length(physical_line, max_line_length, multiline, line_number, noqa)` to solve the following problem:
r"""Limit all lines to a maximum of 79 characters. There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices looks ugly. Therefore, please limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. Reports error E501.
Here is the function:
def maximum_line_length(physical_line, max_line_length, multiline,
line_number, noqa):
r"""Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to
have several windows side-by-side. The default wrapping on such
devices looks ugly. Therefore, please limit all lines to a maximum
of 79 characters. For flowing long blocks of text (docstrings or
comments), limiting the length to 72 characters is recommended.
Reports error E501.
"""
line = physical_line.rstrip()
length = len(line)
if length > max_line_length and not noqa:
# Special case: ignore long shebang lines.
if line_number == 1 and line.startswith('#!'):
return
# Special case for long URLs in multi-line docstrings or
# comments, but still report the error when the 72 first chars
# are whitespaces.
chunks = line.split()
if ((len(chunks) == 1 and multiline) or
(len(chunks) == 2 and chunks[0] == '#')) and \
len(line) - len(chunks[-1]) < max_line_length - 7:
return
if length > max_line_length:
return (max_line_length, "E501 line too long "
"(%d > %d characters)" % (length, max_line_length)) | r"""Limit all lines to a maximum of 79 characters. There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices looks ugly. Therefore, please limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. Reports error E501. |
177,033 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
BLANK_LINES_CONFIG = {
# Top level class and function.
'top_level': 2,
# Methods and nested class and function.
'method': 1,
}
DOCSTRING_REGEX = re.compile(r'u?r?["\']')
STARTSWITH_DEF_REGEX = re.compile(r'^(async\s+def|def)\b')
STARTSWITH_TOP_LEVEL_REGEX = re.compile(r'^(async\s+def\s+|def\s+|class\s+|@)')
def _is_one_liner(logical_line, indent_level, lines, line_number):
if not STARTSWITH_TOP_LEVEL_REGEX.match(logical_line):
return False
line_idx = line_number - 1
if line_idx < 1:
prev_indent = 0
else:
prev_indent = expand_indent(lines[line_idx - 1])
if prev_indent > indent_level:
return False
while line_idx < len(lines):
line = lines[line_idx].strip()
if not line.startswith('@') and STARTSWITH_TOP_LEVEL_REGEX.match(line):
break
else:
line_idx += 1
else:
return False # invalid syntax: EOF while searching for def/class
next_idx = line_idx + 1
while next_idx < len(lines):
if lines[next_idx].strip():
break
else:
next_idx += 1
else:
return True # line is last in the file
return expand_indent(lines[next_idx]) <= indent_level
def expand_indent(line):
r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16
"""
line = line.rstrip('\n\r')
if '\t' not in line:
return len(line) - len(line.lstrip())
result = 0
for char in line:
if char == '\t':
result = result // 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result
The provided code snippet includes necessary dependencies for implementing the `blank_lines` function. Write a Python function `def blank_lines(logical_line, blank_lines, indent_level, line_number, blank_before, previous_logical, previous_unindented_logical_line, previous_indent_level, lines)` to solve the following problem:
r"""Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line. Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). Use blank lines in functions, sparingly, to indicate logical sections. Okay: def a():\n pass\n\n\ndef b():\n pass Okay: def a():\n pass\n\n\nasync def b():\n pass Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass Okay: default = 1\nfoo = 1 Okay: classify = 1\nfoo = 1 E301: class Foo:\n b = 0\n def bar():\n pass E302: def a():\n pass\n\ndef b(n):\n pass E302: def a():\n pass\n\nasync def b(n):\n pass E303: def a():\n pass\n\n\n\ndef b(n):\n pass E303: def a():\n\n\n\n pass E304: @decorator\n\ndef a():\n pass E305: def a():\n pass\na() E306: def a():\n def b():\n pass\n def c():\n pass
Here is the function:
def blank_lines(logical_line, blank_lines, indent_level, line_number,
blank_before, previous_logical,
previous_unindented_logical_line, previous_indent_level,
lines):
r"""Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical
sections.
Okay: def a():\n pass\n\n\ndef b():\n pass
Okay: def a():\n pass\n\n\nasync def b():\n pass
Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
Okay: default = 1\nfoo = 1
Okay: classify = 1\nfoo = 1
E301: class Foo:\n b = 0\n def bar():\n pass
E302: def a():\n pass\n\ndef b(n):\n pass
E302: def a():\n pass\n\nasync def b(n):\n pass
E303: def a():\n pass\n\n\n\ndef b(n):\n pass
E303: def a():\n\n\n\n pass
E304: @decorator\n\ndef a():\n pass
E305: def a():\n pass\na()
E306: def a():\n def b():\n pass\n def c():\n pass
""" # noqa
top_level_lines = BLANK_LINES_CONFIG['top_level']
method_lines = BLANK_LINES_CONFIG['method']
if not previous_logical and blank_before < top_level_lines:
return # Don't expect blank lines before the first line
if previous_logical.startswith('@'):
if blank_lines:
yield 0, "E304 blank lines found after function decorator"
elif (blank_lines > top_level_lines or
(indent_level and blank_lines == method_lines + 1)
):
yield 0, "E303 too many blank lines (%d)" % blank_lines
elif STARTSWITH_TOP_LEVEL_REGEX.match(logical_line):
# allow a group of one-liners
if (
_is_one_liner(logical_line, indent_level, lines, line_number) and
blank_before == 0
):
return
if indent_level:
if not (blank_before == method_lines or
previous_indent_level < indent_level or
DOCSTRING_REGEX.match(previous_logical)
):
ancestor_level = indent_level
nested = False
# Search backwards for a def ancestor or tree root
# (top level).
for line in lines[line_number - top_level_lines::-1]:
if line.strip() and expand_indent(line) < ancestor_level:
ancestor_level = expand_indent(line)
nested = STARTSWITH_DEF_REGEX.match(line.lstrip())
if nested or ancestor_level == 0:
break
if nested:
yield 0, "E306 expected %s blank line before a " \
"nested definition, found 0" % (method_lines,)
else:
yield 0, "E301 expected {} blank line, found 0".format(
method_lines)
elif blank_before != top_level_lines:
yield 0, "E302 expected %s blank lines, found %d" % (
top_level_lines, blank_before)
elif (logical_line and
not indent_level and
blank_before != top_level_lines and
previous_unindented_logical_line.startswith(('def ', 'class '))
):
yield 0, "E305 expected %s blank lines after " \
"class or function definition, found %d" % (
top_level_lines, blank_before) | r"""Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line. Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). Use blank lines in functions, sparingly, to indicate logical sections. Okay: def a():\n pass\n\n\ndef b():\n pass Okay: def a():\n pass\n\n\nasync def b():\n pass Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass Okay: default = 1\nfoo = 1 Okay: classify = 1\nfoo = 1 E301: class Foo:\n b = 0\n def bar():\n pass E302: def a():\n pass\n\ndef b(n):\n pass E302: def a():\n pass\n\nasync def b(n):\n pass E303: def a():\n pass\n\n\n\ndef b(n):\n pass E303: def a():\n\n\n\n pass E304: @decorator\n\ndef a():\n pass E305: def a():\n pass\na() E306: def a():\n def b():\n pass\n def c():\n pass |
177,034 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[\[({][ \t]|[ \t][\]}),;:](?!=)')
The provided code snippet includes necessary dependencies for implementing the `extraneous_whitespace` function. Write a Python function `def extraneous_whitespace(logical_line)` to solve the following problem:
r"""Avoid extraneous whitespace. Avoid extraneous whitespace in these situations: - Immediately inside parentheses, brackets or braces. - Immediately before a comma, semicolon, or colon. Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2}) E201: spam(ham[ 1], {eggs: 2}) E201: spam(ham[1], { eggs: 2}) E202: spam(ham[1], {eggs: 2} ) E202: spam(ham[1 ], {eggs: 2}) E202: spam(ham[1], {eggs: 2 }) E203: if x == 4: print x, y; x, y = y , x E203: if x == 4: print x, y ; x, y = y, x E203: if x == 4 : print x, y; x, y = y, x
Here is the function:
def extraneous_whitespace(logical_line):
r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in these situations:
- Immediately inside parentheses, brackets or braces.
- Immediately before a comma, semicolon, or colon.
Okay: spam(ham[1], {eggs: 2})
E201: spam( ham[1], {eggs: 2})
E201: spam(ham[ 1], {eggs: 2})
E201: spam(ham[1], { eggs: 2})
E202: spam(ham[1], {eggs: 2} )
E202: spam(ham[1 ], {eggs: 2})
E202: spam(ham[1], {eggs: 2 })
E203: if x == 4: print x, y; x, y = y , x
E203: if x == 4: print x, y ; x, y = y, x
E203: if x == 4 : print x, y; x, y = y, x
"""
line = logical_line
for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line):
text = match.group()
char = text.strip()
found = match.start()
if text[-1].isspace():
# assert char in '([{'
yield found + 1, "E201 whitespace after '%s'" % char
elif line[found - 1] != ',':
code = ('E202' if char in '}])' else 'E203') # if char in ',;:'
yield found, f"{code} whitespace before '{char}'" | r"""Avoid extraneous whitespace. Avoid extraneous whitespace in these situations: - Immediately inside parentheses, brackets or braces. - Immediately before a comma, semicolon, or colon. Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2}) E201: spam(ham[ 1], {eggs: 2}) E201: spam(ham[1], { eggs: 2}) E202: spam(ham[1], {eggs: 2} ) E202: spam(ham[1 ], {eggs: 2}) E202: spam(ham[1], {eggs: 2 }) E203: if x == 4: print x, y; x, y = y , x E203: if x == 4: print x, y ; x, y = y, x E203: if x == 4 : print x, y; x, y = y, x |
177,035 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
KEYWORD_REGEX = re.compile(r'(\s*)\b(?:%s)\b(\s*)' % r'|'.join(KEYWORDS))
The provided code snippet includes necessary dependencies for implementing the `whitespace_around_keywords` function. Write a Python function `def whitespace_around_keywords(logical_line)` to solve the following problem:
r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False
Here is the function:
def whitespace_around_keywords(logical_line):
r"""Avoid extraneous whitespace around keywords.
Okay: True and False
E271: True and False
E272: True and False
E273: True and\tFalse
E274: True\tand False
"""
for match in KEYWORD_REGEX.finditer(logical_line):
before, after = match.groups()
if '\t' in before:
yield match.start(1), "E274 tab before keyword"
elif len(before) > 1:
yield match.start(1), "E272 multiple spaces before keyword"
if '\t' in after:
yield match.start(2), "E273 tab after keyword"
elif len(after) > 1:
yield match.start(2), "E271 multiple spaces after keyword" | r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False |
177,036 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
SINGLETONS = frozenset(['False', 'None', 'True'])
The provided code snippet includes necessary dependencies for implementing the `missing_whitespace_after_keyword` function. Write a Python function `def missing_whitespace_after_keyword(logical_line, tokens)` to solve the following problem:
r"""Keywords should be followed by whitespace. Okay: from foo import (bar, baz) E275: from foo import(bar, baz) E275: from importable.module import(bar, baz) E275: if(foo): bar
Here is the function:
def missing_whitespace_after_keyword(logical_line, tokens):
r"""Keywords should be followed by whitespace.
Okay: from foo import (bar, baz)
E275: from foo import(bar, baz)
E275: from importable.module import(bar, baz)
E275: if(foo): bar
"""
for tok0, tok1 in zip(tokens, tokens[1:]):
# This must exclude the True/False/None singletons, which can
# appear e.g. as "if x is None:", and async/await, which were
# valid identifier names in old Python versions.
if (tok0.end == tok1.start and
keyword.iskeyword(tok0.string) and
tok0.string not in SINGLETONS and
tok0.string not in ('async', 'await') and
not (tok0.string == 'except' and tok1.string == '*') and
not (tok0.string == 'yield' and tok1.string == ')') and
tok1.string not in ':\n'):
yield tok0.end, "E275 missing whitespace after keyword" | r"""Keywords should be followed by whitespace. Okay: from foo import (bar, baz) E275: from foo import(bar, baz) E275: from importable.module import(bar, baz) E275: if(foo): bar |
177,037 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
if (
sys.version_info < (3, 10) and
callable(getattr(tokenize, '_compile', None))
): # pragma: no cover (<py310)
tokenize._compile = lru_cache()(tokenize._compile) # type: ignore
try:
if sys.platform == 'win32':
USER_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
USER_CONFIG = os.path.join(
os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
'pycodestyle'
)
except ImportError:
USER_CONFIG = None
WHITESPACE = frozenset(' \t\xa0')
The provided code snippet includes necessary dependencies for implementing the `missing_whitespace` function. Write a Python function `def missing_whitespace(logical_line)` to solve the following problem:
r"""Each comma, semicolon or colon should be followed by whitespace. Okay: [a, b] Okay: (3,) Okay: a[3,] = 1 Okay: a[1:4] Okay: a[:4] Okay: a[1:] Okay: a[1:4:2] E231: ['a','b'] E231: foo(bar,baz) E231: [{'a':'b'}]
Here is the function:
def missing_whitespace(logical_line):
r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[3,] = 1
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}]
"""
line = logical_line
for index in range(len(line) - 1):
char = line[index]
next_char = line[index + 1]
if char in ',;:' and next_char not in WHITESPACE:
before = line[:index]
if char == ':' and before.count('[') > before.count(']') and \
before.rfind('{') < before.rfind('['):
continue # Slice syntax, no space required
if char == ',' and next_char in ')]':
continue # Allow tuple with only one element: (3,)
if char == ':' and next_char == '=' and sys.version_info >= (3, 8):
continue # Allow assignment expression
yield index, "E231 missing whitespace after '%s'" % char | r"""Each comma, semicolon or colon should be followed by whitespace. Okay: [a, b] Okay: (3,) Okay: a[3,] = 1 Okay: a[1:4] Okay: a[:4] Okay: a[1:] Okay: a[1:4:2] E231: ['a','b'] E231: foo(bar,baz) E231: [{'a':'b'}] |
177,038 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE])
def expand_indent(line):
r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16
"""
line = line.rstrip('\n\r')
if '\t' not in line:
return len(line) - len(line.lstrip())
result = 0
for char in line:
if char == '\t':
result = result // 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result
The provided code snippet includes necessary dependencies for implementing the `continued_indentation` function. Write a Python function `def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, indent_size, noqa, verbose)` to solve the following problem:
r"""Continuation lines indentation. Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent these considerations should be applied: - there should be no arguments on the first line, and - further indentation should be used to clearly distinguish itself as a continuation line. Okay: a = (\n) E123: a = (\n ) Okay: a = (\n 42) E121: a = (\n 42) E122: a = (\n42) E123: a = (\n 42\n ) E124: a = (24,\n 42\n) E125: if (\n b):\n pass E126: a = (\n 42) E127: a = (24,\n 42) E128: a = (24,\n 42) E129: if (a or\n b):\n pass E131: a = (\n 42\n 24)
Here is the function:
def continued_indentation(logical_line, tokens, indent_level, hang_closing,
indent_char, indent_size, noqa, verbose):
r"""Continuation lines indentation.
Continuation lines should align wrapped elements either vertically
using Python's implicit line joining inside parentheses, brackets
and braces, or using a hanging indent.
When using a hanging indent these considerations should be applied:
- there should be no arguments on the first line, and
- further indentation should be used to clearly distinguish itself
as a continuation line.
Okay: a = (\n)
E123: a = (\n )
Okay: a = (\n 42)
E121: a = (\n 42)
E122: a = (\n42)
E123: a = (\n 42\n )
E124: a = (24,\n 42\n)
E125: if (\n b):\n pass
E126: a = (\n 42)
E127: a = (24,\n 42)
E128: a = (24,\n 42)
E129: if (a or\n b):\n pass
E131: a = (\n 42\n 24)
"""
first_row = tokens[0][2][0]
nrows = 1 + tokens[-1][2][0] - first_row
if noqa or nrows == 1:
return
# indent_next tells us whether the next block is indented; assuming
# that it is indented by 4 spaces, then we should not allow 4-space
# indents on the final continuation line; in turn, some other
# indents are allowed to have an extra 4 spaces.
indent_next = logical_line.endswith(':')
row = depth = 0
valid_hangs = (indent_size,) if indent_char != '\t' \
else (indent_size, indent_size * 2)
# remember how many brackets were opened on each line
parens = [0] * nrows
# relative indents of physical lines
rel_indent = [0] * nrows
# for each depth, collect a list of opening rows
open_rows = [[0]]
# for each depth, memorize the hanging indentation
hangs = [None]
# visual indents
indent_chances = {}
last_indent = tokens[0][2]
visual_indent = None
last_token_multiline = False
# for each depth, memorize the visual indent column
indent = [last_indent[1]]
if verbose >= 3:
print(">>> " + tokens[0][4].rstrip())
for token_type, text, start, end, line in tokens:
newline = row < start[0] - first_row
if newline:
row = start[0] - first_row
newline = not last_token_multiline and token_type not in NEWLINE
if newline:
# this is the beginning of a continuation line.
last_indent = start
if verbose >= 3:
print("... " + line.rstrip())
# record the initial indent.
rel_indent[row] = expand_indent(line) - indent_level
# identify closing bracket
close_bracket = (token_type == tokenize.OP and text in ']})')
# is the indent relative to an opening bracket line?
for open_row in reversed(open_rows[depth]):
hang = rel_indent[row] - rel_indent[open_row]
hanging_indent = hang in valid_hangs
if hanging_indent:
break
if hangs[depth]:
hanging_indent = (hang == hangs[depth])
# is there any chance of visual indent?
visual_indent = (not close_bracket and hang > 0 and
indent_chances.get(start[1]))
if close_bracket and indent[depth]:
# closing bracket for visual indent
if start[1] != indent[depth]:
yield (start, "E124 closing bracket does not match "
"visual indentation")
elif close_bracket and not hang:
# closing bracket matches indentation of opening
# bracket's line
if hang_closing:
yield start, "E133 closing bracket is missing indentation"
elif indent[depth] and start[1] < indent[depth]:
if visual_indent is not True:
# visual indent is broken
yield (start, "E128 continuation line "
"under-indented for visual indent")
elif hanging_indent or (indent_next and
rel_indent[row] == 2 * indent_size):
# hanging indent is verified
if close_bracket and not hang_closing:
yield (start, "E123 closing bracket does not match "
"indentation of opening bracket's line")
hangs[depth] = hang
elif visual_indent is True:
# visual indent is verified
indent[depth] = start[1]
elif visual_indent in (text, str):
# ignore token lined up with matching one from a
# previous line
pass
else:
# indent is broken
if hang <= 0:
error = "E122", "missing indentation or outdented"
elif indent[depth]:
error = "E127", "over-indented for visual indent"
elif not close_bracket and hangs[depth]:
error = "E131", "unaligned for hanging indent"
else:
hangs[depth] = hang
if hang > indent_size:
error = "E126", "over-indented for hanging indent"
else:
error = "E121", "under-indented for hanging indent"
yield start, "%s continuation line %s" % error
# look for visual indenting
if (parens[row] and
token_type not in (tokenize.NL, tokenize.COMMENT) and
not indent[depth]):
indent[depth] = start[1]
indent_chances[start[1]] = True
if verbose >= 4:
print(f"bracket depth {depth} indent to {start[1]}")
# deal with implicit string concatenation
elif (token_type in (tokenize.STRING, tokenize.COMMENT) or
text in ('u', 'ur', 'b', 'br')):
indent_chances[start[1]] = str
# visual indent after assert/raise/with
elif not row and not depth and text in ["assert", "raise", "with"]:
indent_chances[end[1] + 1] = True
# special case for the "if" statement because len("if (") == 4
elif not indent_chances and not row and not depth and text == 'if':
indent_chances[end[1] + 1] = True
elif text == ':' and line[end[1]:].isspace():
open_rows[depth].append(row)
# keep track of bracket depth
if token_type == tokenize.OP:
if text in '([{':
depth += 1
indent.append(0)
hangs.append(None)
if len(open_rows) == depth:
open_rows.append([])
open_rows[depth].append(row)
parens[row] += 1
if verbose >= 4:
print("bracket depth %s seen, col %s, visual min = %s" %
(depth, start[1], indent[depth]))
elif text in ')]}' and depth > 0:
# parent indents should not be more than this one
prev_indent = indent.pop() or last_indent[1]
hangs.pop()
for d in range(depth):
if indent[d] > prev_indent:
indent[d] = 0
for ind in list(indent_chances):
if ind >= prev_indent:
del indent_chances[ind]
del open_rows[depth + 1:]
depth -= 1
if depth:
indent_chances[indent[depth]] = True
for idx in range(row, -1, -1):
if parens[idx]:
parens[idx] -= 1
break
assert len(indent) == depth + 1
if start[1] not in indent_chances:
# allow lining up tokens
indent_chances[start[1]] = text
last_token_multiline = (start[0] != end[0])
if last_token_multiline:
rel_indent[end[0] - first_row] = rel_indent[row]
if indent_next and expand_indent(line) == indent_level + indent_size:
pos = (start[0], indent[0] + indent_size)
if visual_indent:
code = "E129 visually indented line"
else:
code = "E125 continuation line"
yield pos, "%s with same indent as next logical line" % code | r"""Continuation lines indentation. Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent these considerations should be applied: - there should be no arguments on the first line, and - further indentation should be used to clearly distinguish itself as a continuation line. Okay: a = (\n) E123: a = (\n ) Okay: a = (\n 42) E121: a = (\n 42) E122: a = (\n42) E123: a = (\n 42\n ) E124: a = (24,\n 42\n) E125: if (\n b):\n pass E126: a = (\n 42) E127: a = (24,\n 42) E128: a = (24,\n 42) E129: if (a or\n b):\n pass E131: a = (\n 42\n 24) |
177,039 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
if (
sys.version_info < (3, 10) and
callable(getattr(tokenize, '_compile', None))
): # pragma: no cover (<py310)
tokenize._compile = lru_cache()(tokenize._compile) # type: ignore
try:
if sys.platform == 'win32':
USER_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
USER_CONFIG = os.path.join(
os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
'pycodestyle'
)
except ImportError:
USER_CONFIG = None
The provided code snippet includes necessary dependencies for implementing the `whitespace_before_parameters` function. Write a Python function `def whitespace_before_parameters(logical_line, tokens)` to solve the following problem:
r"""Avoid extraneous whitespace. Avoid extraneous whitespace in the following situations: - before the open parenthesis that starts the argument list of a function call. - before the open parenthesis that starts an indexing or slicing. Okay: spam(1) E211: spam (1) Okay: dict['key'] = list[index] E211: dict ['key'] = list[index] E211: dict['key'] = list [index]
Here is the function:
def whitespace_before_parameters(logical_line, tokens):
r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in the following situations:
- before the open parenthesis that starts the argument list of a
function call.
- before the open parenthesis that starts an indexing or slicing.
Okay: spam(1)
E211: spam (1)
Okay: dict['key'] = list[index]
E211: dict ['key'] = list[index]
E211: dict['key'] = list [index]
"""
prev_type, prev_text, __, prev_end, __ = tokens[0]
for index in range(1, len(tokens)):
token_type, text, start, end, __ = tokens[index]
if (
token_type == tokenize.OP and
text in '([' and
start != prev_end and
(prev_type == tokenize.NAME or prev_text in '}])') and
# Syntax "class A (B):" is allowed, but avoid it
(index < 2 or tokens[index - 2][1] != 'class') and
# Allow "return (a.foo for a in range(5))"
not keyword.iskeyword(prev_text) and
# 'match' and 'case' are only soft keywords
(
sys.version_info < (3, 9) or
not keyword.issoftkeyword(prev_text)
)
):
yield prev_end, "E211 whitespace before '%s'" % text
prev_type = token_type
prev_text = text
prev_end = end | r"""Avoid extraneous whitespace. Avoid extraneous whitespace in the following situations: - before the open parenthesis that starts the argument list of a function call. - before the open parenthesis that starts an indexing or slicing. Okay: spam(1) E211: spam (1) Okay: dict['key'] = list[index] E211: dict ['key'] = list[index] E211: dict['key'] = list [index] |
177,040 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
OPERATOR_REGEX = re.compile(r'(?:[^,\s])(\s*)(?:[-+*/|!<=>%&^]+|:=)(\s*)')
The provided code snippet includes necessary dependencies for implementing the `whitespace_around_operator` function. Write a Python function `def whitespace_around_operator(logical_line)` to solve the following problem:
r"""Avoid extraneous whitespace around an operator. Okay: a = 12 + 3 E221: a = 4 + 5 E222: a = 4 + 5 E223: a = 4\t+ 5 E224: a = 4 +\t5
Here is the function:
def whitespace_around_operator(logical_line):
r"""Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3
E221: a = 4 + 5
E222: a = 4 + 5
E223: a = 4\t+ 5
E224: a = 4 +\t5
"""
for match in OPERATOR_REGEX.finditer(logical_line):
before, after = match.groups()
if '\t' in before:
yield match.start(1), "E223 tab before operator"
elif len(before) > 1:
yield match.start(1), "E221 multiple spaces before operator"
if '\t' in after:
yield match.start(2), "E224 tab after operator"
elif len(after) > 1:
yield match.start(2), "E222 multiple spaces after operator" | r"""Avoid extraneous whitespace around an operator. Okay: a = 12 + 3 E221: a = 4 + 5 E222: a = 4 + 5 E223: a = 4\t+ 5 E224: a = 4 +\t5 |
177,041 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
if (
sys.version_info < (3, 10) and
callable(getattr(tokenize, '_compile', None))
): # pragma: no cover (<py310)
tokenize._compile = lru_cache()(tokenize._compile) # type: ignore
try:
if sys.platform == 'win32':
USER_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
USER_CONFIG = os.path.join(
os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
'pycodestyle'
)
except ImportError:
USER_CONFIG = None
KEYWORDS = frozenset(keyword.kwlist + ['print', 'async']) - SINGLETONS
UNARY_OPERATORS = frozenset(['>>', '**', '*', '+', '-'])
ARITHMETIC_OP = frozenset(['**', '*', '/', '//', '+', '-', '@'])
WS_OPTIONAL_OPERATORS = ARITHMETIC_OP.union(['^', '&', '|', '<<', '>>', '%'])
WS_NEEDED_OPERATORS = frozenset([
'**=', '*=', '/=', '//=', '+=', '-=', '!=', '<>', '<', '>',
'%=', '^=', '&=', '|=', '==', '<=', '>=', '<<=', '>>=', '=',
'and', 'in', 'is', 'or', '->'] +
ASSIGNMENT_EXPRESSION_OP)
SKIP_COMMENTS = SKIP_TOKENS.union([tokenize.COMMENT, tokenize.ERRORTOKEN])
The provided code snippet includes necessary dependencies for implementing the `missing_whitespace_around_operator` function. Write a Python function `def missing_whitespace_around_operator(logical_line, tokens)` to solve the following problem:
r"""Surround operators with a single space on either side. - Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), Booleans (and, or, not). - If operators with different priorities are used, consider adding whitespace around the operators with the lowest priorities. Okay: i = i + 1 Okay: submitted += 1 Okay: x = x * 2 - 1 Okay: hypot2 = x * x + y * y Okay: c = (a + b) * (a - b) Okay: foo(bar, key='word', *args, **kwargs) Okay: alpha[:-i] E225: i=i+1 E225: submitted +=1 E225: x = x /2 - 1 E225: z = x **y E225: z = 1and 1 E226: c = (a+b) * (a-b) E226: hypot2 = x*x + y*y E227: c = a|b E228: msg = fmt%(errno, errmsg)
Here is the function:
def missing_whitespace_around_operator(logical_line, tokens):
r"""Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
Booleans (and, or, not).
- If operators with different priorities are used, consider adding
whitespace around the operators with the lowest priorities.
Okay: i = i + 1
Okay: submitted += 1
Okay: x = x * 2 - 1
Okay: hypot2 = x * x + y * y
Okay: c = (a + b) * (a - b)
Okay: foo(bar, key='word', *args, **kwargs)
Okay: alpha[:-i]
E225: i=i+1
E225: submitted +=1
E225: x = x /2 - 1
E225: z = x **y
E225: z = 1and 1
E226: c = (a+b) * (a-b)
E226: hypot2 = x*x + y*y
E227: c = a|b
E228: msg = fmt%(errno, errmsg)
"""
parens = 0
need_space = False
prev_type = tokenize.OP
prev_text = prev_end = None
operator_types = (tokenize.OP, tokenize.NAME)
for token_type, text, start, end, line in tokens:
if token_type in SKIP_COMMENTS:
continue
if text in ('(', 'lambda'):
parens += 1
elif text == ')':
parens -= 1
if need_space:
if start != prev_end:
# Found a (probably) needed space
if need_space is not True and not need_space[1]:
yield (need_space[0],
"E225 missing whitespace around operator")
need_space = False
elif text == '>' and prev_text in ('<', '-'):
# Tolerate the "<>" operator, even if running Python 3
# Deal with Python 3's annotated return value "->"
pass
elif (
# def f(a, /, b):
# ^
# def f(a, b, /):
# ^
# f = lambda a, /:
# ^
prev_text == '/' and text in {',', ')', ':'} or
# def f(a, b, /):
# ^
prev_text == ')' and text == ':'
):
# Tolerate the "/" operator in function definition
# For more info see PEP570
pass
else:
if need_space is True or need_space[1]:
# A needed trailing space was not found
yield prev_end, "E225 missing whitespace around operator"
elif prev_text != '**':
code, optype = 'E226', 'arithmetic'
if prev_text == '%':
code, optype = 'E228', 'modulo'
elif prev_text not in ARITHMETIC_OP:
code, optype = 'E227', 'bitwise or shift'
yield (need_space[0], "%s missing whitespace "
"around %s operator" % (code, optype))
need_space = False
elif token_type in operator_types and prev_end is not None:
if text == '=' and parens:
# Allow keyword args or defaults: foo(bar=None).
pass
elif text in WS_NEEDED_OPERATORS:
need_space = True
elif text in UNARY_OPERATORS:
# Check if the operator is used as a binary operator
# Allow unary operators: -123, -x, +1.
# Allow argument unpacking: foo(*args, **kwargs).
if prev_type == tokenize.OP and prev_text in '}])' or (
prev_type != tokenize.OP and
prev_text not in KEYWORDS and (
sys.version_info < (3, 9) or
not keyword.issoftkeyword(prev_text)
)
):
need_space = None
elif text in WS_OPTIONAL_OPERATORS:
need_space = None
if need_space is None:
# Surrounding space is optional, but ensure that
# trailing space matches opening space
need_space = (prev_end, start != prev_end)
elif need_space and start == prev_end:
# A needed opening space was not found
yield prev_end, "E225 missing whitespace around operator"
need_space = False
prev_type = token_type
prev_text = text
prev_end = end | r"""Surround operators with a single space on either side. - Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), Booleans (and, or, not). - If operators with different priorities are used, consider adding whitespace around the operators with the lowest priorities. Okay: i = i + 1 Okay: submitted += 1 Okay: x = x * 2 - 1 Okay: hypot2 = x * x + y * y Okay: c = (a + b) * (a - b) Okay: foo(bar, key='word', *args, **kwargs) Okay: alpha[:-i] E225: i=i+1 E225: submitted +=1 E225: x = x /2 - 1 E225: z = x **y E225: z = 1and 1 E226: c = (a+b) * (a-b) E226: hypot2 = x*x + y*y E227: c = a|b E228: msg = fmt%(errno, errmsg) |
177,042 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
WHITESPACE_AFTER_COMMA_REGEX = re.compile(r'[,;:]\s*(?: |\t)')
The provided code snippet includes necessary dependencies for implementing the `whitespace_around_comma` function. Write a Python function `def whitespace_around_comma(logical_line)` to solve the following problem:
r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2)
Here is the function:
def whitespace_around_comma(logical_line):
r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2)
"""
line = logical_line
for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
found = m.start() + 1
if '\t' in m.group():
yield found, "E242 tab after '%s'" % m.group()[0]
else:
yield found, "E241 multiple spaces after '%s'" % m.group()[0] | r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2) |
177,043 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
STARTSWITH_DEF_REGEX = re.compile(r'^(async\s+def|def)\b')
The provided code snippet includes necessary dependencies for implementing the `whitespace_around_named_parameter_equals` function. Write a Python function `def whitespace_around_named_parameter_equals(logical_line, tokens)` to solve the following problem:
r"""Don't use spaces around the '=' sign in function arguments. Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value, except when using a type annotation. Okay: def complex(real, imag=0.0): Okay: return magic(r=real, i=imag) Okay: boolean(a == b) Okay: boolean(a != b) Okay: boolean(a <= b) Okay: boolean(a >= b) Okay: def foo(arg: int = 42): Okay: async def foo(arg: int = 42): E251: def complex(real, imag = 0.0): E251: return magic(r = real, i = imag) E252: def complex(real, image: float=0.0):
Here is the function:
def whitespace_around_named_parameter_equals(logical_line, tokens):
r"""Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a
keyword argument or a default parameter value, except when
using a type annotation.
Okay: def complex(real, imag=0.0):
Okay: return magic(r=real, i=imag)
Okay: boolean(a == b)
Okay: boolean(a != b)
Okay: boolean(a <= b)
Okay: boolean(a >= b)
Okay: def foo(arg: int = 42):
Okay: async def foo(arg: int = 42):
E251: def complex(real, imag = 0.0):
E251: return magic(r = real, i = imag)
E252: def complex(real, image: float=0.0):
"""
parens = 0
no_space = False
require_space = False
prev_end = None
annotated_func_arg = False
in_def = bool(STARTSWITH_DEF_REGEX.match(logical_line))
message = "E251 unexpected spaces around keyword / parameter equals"
missing_message = "E252 missing whitespace around parameter equals"
for token_type, text, start, end, line in tokens:
if token_type == tokenize.NL:
continue
if no_space:
no_space = False
if start != prev_end:
yield (prev_end, message)
if require_space:
require_space = False
if start == prev_end:
yield (prev_end, missing_message)
if token_type == tokenize.OP:
if text in '([':
parens += 1
elif text in ')]':
parens -= 1
elif in_def and text == ':' and parens == 1:
annotated_func_arg = True
elif parens == 1 and text == ',':
annotated_func_arg = False
elif parens and text == '=':
if annotated_func_arg and parens == 1:
require_space = True
if start == prev_end:
yield (prev_end, missing_message)
else:
no_space = True
if start != prev_end:
yield (prev_end, message)
if not parens:
annotated_func_arg = False
prev_end = end | r"""Don't use spaces around the '=' sign in function arguments. Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value, except when using a type annotation. Okay: def complex(real, imag=0.0): Okay: return magic(r=real, i=imag) Okay: boolean(a == b) Okay: boolean(a != b) Okay: boolean(a <= b) Okay: boolean(a >= b) Okay: def foo(arg: int = 42): Okay: async def foo(arg: int = 42): E251: def complex(real, imag = 0.0): E251: return magic(r = real, i = imag) E252: def complex(real, image: float=0.0): |
177,044 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
WHITESPACE = frozenset(' \t\xa0')
The provided code snippet includes necessary dependencies for implementing the `whitespace_before_comment` function. Write a Python function `def whitespace_before_comment(logical_line, tokens)` to solve the following problem:
Separate inline comments by at least two spaces. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Each line of a block comment starts with a # and one or multiple spaces as there can be indented text inside the comment. Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x Okay: # Block comments: Okay: # - Block comment list Okay: # \xa0- Block comment list E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x E262: x = x + 1 # \xa0Increment x E265: #Block comment E266: ### Block comment
Here is the function:
def whitespace_before_comment(logical_line, tokens):
"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement.
Inline comments should be separated by at least two spaces from the
statement. They should start with a # and a single space.
Each line of a block comment starts with a # and one or multiple
spaces as there can be indented text inside the comment.
Okay: x = x + 1 # Increment x
Okay: x = x + 1 # Increment x
Okay: # Block comments:
Okay: # - Block comment list
Okay: # \xa0- Block comment list
E261: x = x + 1 # Increment x
E262: x = x + 1 #Increment x
E262: x = x + 1 # Increment x
E262: x = x + 1 # \xa0Increment x
E265: #Block comment
E266: ### Block comment
"""
prev_end = (0, 0)
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
inline_comment = line[:start[1]].strip()
if inline_comment:
if prev_end[0] == start[0] and start[1] < prev_end[1] + 2:
yield (prev_end,
"E261 at least two spaces before inline comment")
symbol, sp, comment = text.partition(' ')
bad_prefix = symbol not in '#:' and (symbol.lstrip('#')[:1] or '#')
if inline_comment:
if bad_prefix or comment[:1] in WHITESPACE:
yield start, "E262 inline comment should start with '# '"
elif bad_prefix and (bad_prefix != '!' or start[0] > 1):
if bad_prefix != '#':
yield start, "E265 block comment should start with '# '"
elif comment:
yield start, "E266 too many leading '#' for block comment"
elif token_type != tokenize.NL:
prev_end = end | Separate inline comments by at least two spaces. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Each line of a block comment starts with a # and one or multiple spaces as there can be indented text inside the comment. Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x Okay: # Block comments: Okay: # - Block comment list Okay: # \xa0- Block comment list E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x E262: x = x + 1 # \xa0Increment x E265: #Block comment E266: ### Block comment |
177,045 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `imports_on_separate_lines` function. Write a Python function `def imports_on_separate_lines(logical_line)` to solve the following problem:
r"""Place imports on separate lines. Okay: import os\nimport sys E401: import sys, os Okay: from subprocess import Popen, PIPE Okay: from myclas import MyClass Okay: from foo.bar.yourclass import YourClass Okay: import myclass Okay: import foo.bar.yourclass
Here is the function:
def imports_on_separate_lines(logical_line):
r"""Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import foo.bar.yourclass
"""
line = logical_line
if line.startswith('import '):
found = line.find(',')
if -1 < found and ';' not in line[:found]:
yield found, "E401 multiple imports on one line" | r"""Place imports on separate lines. Okay: import os\nimport sys E401: import sys, os Okay: from subprocess import Popen, PIPE Okay: from myclas import MyClass Okay: from foo.bar.yourclass import YourClass Okay: import myclass Okay: import foo.bar.yourclass |
177,046 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
DUNDER_REGEX = re.compile(r"^__([^\s]+)__(?::\s*[a-zA-Z.0-9_\[\]\"]+)? = ")
The provided code snippet includes necessary dependencies for implementing the `module_imports_on_top_of_file` function. Write a Python function `def module_imports_on_top_of_file( logical_line, indent_level, checker_state, noqa)` to solve the following problem:
r"""Place imports at the top of the file. Always put imports at the top of the file, just after any module comments and docstrings, and before module globals and constants. Okay: import os Okay: # this is a comment\nimport os Okay: '''this is a module docstring'''\nimport os Okay: r'''this is a module docstring'''\nimport os Okay: try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y Okay: try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y E402: a=1\nimport os E402: 'One string'\n"Two string"\nimport os E402: a=1\nfrom sys import x Okay: if x:\n import os
Here is the function:
def module_imports_on_top_of_file(
logical_line, indent_level, checker_state, noqa):
r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module
comments and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is a module docstring'''\nimport os
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y
E402: a=1\nimport os
E402: 'One string'\n"Two string"\nimport os
E402: a=1\nfrom sys import x
Okay: if x:\n import os
""" # noqa
def is_string_literal(line):
if line[0] in 'uUbB':
line = line[1:]
if line and line[0] in 'rR':
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")
allowed_keywords = (
'try', 'except', 'else', 'finally', 'with', 'if', 'elif')
if indent_level: # Allow imports in conditional statement/function
return
if not logical_line: # Allow empty lines or comments
return
if noqa:
return
line = logical_line
if line.startswith('import ') or line.startswith('from '):
if checker_state.get('seen_non_imports', False):
yield 0, "E402 module level import not at top of file"
elif re.match(DUNDER_REGEX, line):
return
elif any(line.startswith(kw) for kw in allowed_keywords):
# Allow certain keywords intermixed with imports in order to
# support conditional or filtered importing
return
elif is_string_literal(line):
# The first literal is a docstring, allow it. Otherwise, report
# error.
if checker_state.get('seen_docstring', False):
checker_state['seen_non_imports'] = True
else:
checker_state['seen_docstring'] = True
else:
checker_state['seen_non_imports'] = True | r"""Place imports at the top of the file. Always put imports at the top of the file, just after any module comments and docstrings, and before module globals and constants. Okay: import os Okay: # this is a comment\nimport os Okay: '''this is a module docstring'''\nimport os Okay: r'''this is a module docstring'''\nimport os Okay: try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y Okay: try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y E402: a=1\nimport os E402: 'One string'\n"Two string"\nimport os E402: a=1\nfrom sys import x Okay: if x:\n import os |
177,047 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
if (
sys.version_info < (3, 10) and
callable(getattr(tokenize, '_compile', None))
): # pragma: no cover (<py310)
tokenize._compile = lru_cache()(tokenize._compile) # type: ignore
try:
if sys.platform == 'win32':
USER_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
USER_CONFIG = os.path.join(
os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
'pycodestyle'
)
except ImportError:
USER_CONFIG = None
LAMBDA_REGEX = re.compile(r'\blambda\b')
STARTSWITH_DEF_REGEX = re.compile(r'^(async\s+def|def)\b')
STARTSWITH_INDENT_STATEMENT_REGEX = re.compile(
r'^\s*({})\b'.format('|'.join(s.replace(' ', r'\s+') for s in (
'def', 'async def',
'for', 'async for',
'if', 'elif', 'else',
'try', 'except', 'finally',
'with', 'async with',
'class',
'while',
)))
)
def update_counts(s, counts):
r"""Adds one to the counts of each appearance of characters in s,
for characters in counts"""
for char in s:
if char in counts:
counts[char] += 1
The provided code snippet includes necessary dependencies for implementing the `compound_statements` function. Write a Python function `def compound_statements(logical_line)` to solve the following problem:
r"""Compound statements (on the same line) are generally discouraged. While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name. Okay: if foo == 'blah':\n do_blah_thing() Okay: do_one() Okay: do_two() Okay: do_three() E701: if foo == 'blah': do_blah_thing() E701: for x in lst: total += x E701: while t < 10: t = delay() E701: if foo == 'blah': do_blah_thing() E701: else: do_non_blah_thing() E701: try: something() E701: finally: cleanup() E701: if foo == 'blah': one(); two(); three() E702: do_one(); do_two(); do_three() E703: do_four(); # useless semicolon E704: def f(x): return 2*x E731: f = lambda x: 2*x
Here is the function:
def compound_statements(logical_line):
r"""Compound statements (on the same line) are generally
discouraged.
While sometimes it's okay to put an if/for/while with a small body
on the same line, never do this for multi-clause statements.
Also avoid folding such long lines!
Always use a def statement instead of an assignment statement that
binds a lambda expression directly to a name.
Okay: if foo == 'blah':\n do_blah_thing()
Okay: do_one()
Okay: do_two()
Okay: do_three()
E701: if foo == 'blah': do_blah_thing()
E701: for x in lst: total += x
E701: while t < 10: t = delay()
E701: if foo == 'blah': do_blah_thing()
E701: else: do_non_blah_thing()
E701: try: something()
E701: finally: cleanup()
E701: if foo == 'blah': one(); two(); three()
E702: do_one(); do_two(); do_three()
E703: do_four(); # useless semicolon
E704: def f(x): return 2*x
E731: f = lambda x: 2*x
"""
line = logical_line
last_char = len(line) - 1
found = line.find(':')
prev_found = 0
counts = {char: 0 for char in '{}[]()'}
while -1 < found < last_char:
update_counts(line[prev_found:found], counts)
if ((counts['{'] <= counts['}'] and # {'a': 1} (dict)
counts['['] <= counts[']'] and # [1:2] (slice)
counts['('] <= counts[')']) and # (annotation)
not (sys.version_info >= (3, 8) and
line[found + 1] == '=')): # assignment expression
lambda_kw = LAMBDA_REGEX.search(line, 0, found)
if lambda_kw:
before = line[:lambda_kw.start()].rstrip()
if before[-1:] == '=' and before[:-1].strip().isidentifier():
yield 0, ("E731 do not assign a lambda expression, use a "
"def")
break
if STARTSWITH_DEF_REGEX.match(line):
yield 0, "E704 multiple statements on one line (def)"
elif STARTSWITH_INDENT_STATEMENT_REGEX.match(line):
yield found, "E701 multiple statements on one line (colon)"
prev_found = found
found = line.find(':', found + 1)
found = line.find(';')
while -1 < found:
if found < last_char:
yield found, "E702 multiple statements on one line (semicolon)"
else:
yield found, "E703 statement ends with a semicolon"
found = line.find(';', found + 1) | r"""Compound statements (on the same line) are generally discouraged. While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name. Okay: if foo == 'blah':\n do_blah_thing() Okay: do_one() Okay: do_two() Okay: do_three() E701: if foo == 'blah': do_blah_thing() E701: for x in lst: total += x E701: while t < 10: t = delay() E701: if foo == 'blah': do_blah_thing() E701: else: do_non_blah_thing() E701: try: something() E701: finally: cleanup() E701: if foo == 'blah': one(); two(); three() E702: do_one(); do_two(); do_three() E703: do_four(); # useless semicolon E704: def f(x): return 2*x E731: f = lambda x: 2*x |
177,048 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `explicit_line_join` function. Write a Python function `def explicit_line_join(logical_line, tokens)` to solve the following problem:
r"""Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. E502: aaa = [123, \\n 123] E502: aaa = ("bbb " \\n "ccc") Okay: aaa = [123,\n 123] Okay: aaa = ("bbb "\n "ccc") Okay: aaa = "bbb " \\n "ccc" Okay: aaa = 123 # \\
Here is the function:
def explicit_line_join(logical_line, tokens):
r"""Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's
implied line continuation inside parentheses, brackets and braces.
Long lines can be broken over multiple lines by wrapping expressions
in parentheses. These should be used in preference to using a
backslash for line continuation.
E502: aaa = [123, \\n 123]
E502: aaa = ("bbb " \\n "ccc")
Okay: aaa = [123,\n 123]
Okay: aaa = ("bbb "\n "ccc")
Okay: aaa = "bbb " \\n "ccc"
Okay: aaa = 123 # \\
"""
prev_start = prev_end = parens = 0
comment = False
backslash = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
comment = True
if start[0] != prev_start and parens and backslash and not comment:
yield backslash, "E502 the backslash is redundant between brackets"
if end[0] != prev_end:
if line.rstrip('\r\n').endswith('\\'):
backslash = (end[0], len(line.splitlines()[-1]) - 1)
else:
backslash = None
prev_start = prev_end = end[0]
else:
prev_start = start[0]
if token_type == tokenize.OP:
if text in '([{':
parens += 1
elif text in ')]}':
parens -= 1 | r"""Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. E502: aaa = [123, \\n 123] E502: aaa = ("bbb " \\n "ccc") Okay: aaa = [123,\n 123] Okay: aaa = ("bbb "\n "ccc") Okay: aaa = "bbb " \\n "ccc" Okay: aaa = 123 # \\ |
177,049 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
def _is_binary_operator(token_type, text):
return (
token_type == tokenize.OP or
text in {'and', 'or'}
) and (
text not in _SYMBOLIC_OPS
)
def _break_around_binary_operators(tokens):
"""Private function to reduce duplication.
This factors out the shared details between
:func:`break_before_binary_operator` and
:func:`break_after_binary_operator`.
"""
line_break = False
unary_context = True
# Previous non-newline token types and text
previous_token_type = None
previous_text = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
continue
if ('\n' in text or '\r' in text) and token_type != tokenize.STRING:
line_break = True
else:
yield (token_type, text, previous_token_type, previous_text,
line_break, unary_context, start)
unary_context = text in '([{,;'
line_break = False
previous_token_type = token_type
previous_text = text
The provided code snippet includes necessary dependencies for implementing the `break_before_binary_operator` function. Write a Python function `def break_before_binary_operator(logical_line, tokens)` to solve the following problem:
r""" Avoid breaks before binary operators. The preferred place to break around a binary operator is after the operator, not before it. W503: (width == 0\n + height == 0) W503: (width == 0\n and height == 0) W503: var = (1\n & ~2) W503: var = (1\n / -2) W503: var = (1\n + -1\n + -2) Okay: foo(\n -x) Okay: foo(x\n []) Okay: x = '''\n''' + '' Okay: foo(x,\n -y) Okay: foo(x, # comment\n -y)
Here is the function:
def break_before_binary_operator(logical_line, tokens):
r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
W503: var = (1\n & ~2)
W503: var = (1\n / -2)
W503: var = (1\n + -1\n + -2)
Okay: foo(\n -x)
Okay: foo(x\n [])
Okay: x = '''\n''' + ''
Okay: foo(x,\n -y)
Okay: foo(x, # comment\n -y)
"""
for context in _break_around_binary_operators(tokens):
(token_type, text, previous_token_type, previous_text,
line_break, unary_context, start) = context
if (_is_binary_operator(token_type, text) and line_break and
not unary_context and
not _is_binary_operator(previous_token_type,
previous_text)):
yield start, "W503 line break before binary operator" | r""" Avoid breaks before binary operators. The preferred place to break around a binary operator is after the operator, not before it. W503: (width == 0\n + height == 0) W503: (width == 0\n and height == 0) W503: var = (1\n & ~2) W503: var = (1\n / -2) W503: var = (1\n + -1\n + -2) Okay: foo(\n -x) Okay: foo(x\n []) Okay: x = '''\n''' + '' Okay: foo(x,\n -y) Okay: foo(x, # comment\n -y) |
177,050 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
def _is_binary_operator(token_type, text):
return (
token_type == tokenize.OP or
text in {'and', 'or'}
) and (
text not in _SYMBOLIC_OPS
)
def _break_around_binary_operators(tokens):
"""Private function to reduce duplication.
This factors out the shared details between
:func:`break_before_binary_operator` and
:func:`break_after_binary_operator`.
"""
line_break = False
unary_context = True
# Previous non-newline token types and text
previous_token_type = None
previous_text = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
continue
if ('\n' in text or '\r' in text) and token_type != tokenize.STRING:
line_break = True
else:
yield (token_type, text, previous_token_type, previous_text,
line_break, unary_context, start)
unary_context = text in '([{,;'
line_break = False
previous_token_type = token_type
previous_text = text
The provided code snippet includes necessary dependencies for implementing the `break_after_binary_operator` function. Write a Python function `def break_after_binary_operator(logical_line, tokens)` to solve the following problem:
r""" Avoid breaks after binary operators. The preferred place to break around a binary operator is before the operator, not after it. W504: (width == 0 +\n height == 0) W504: (width == 0 and\n height == 0) W504: var = (1 &\n ~2) Okay: foo(\n -x) Okay: foo(x\n []) Okay: x = '''\n''' + '' Okay: x = '' + '''\n''' Okay: foo(x,\n -y) Okay: foo(x, # comment\n -y) The following should be W504 but unary_context is tricky with these Okay: var = (1 /\n -2) Okay: var = (1 +\n -1 +\n -2)
Here is the function:
def break_after_binary_operator(logical_line, tokens):
r"""
Avoid breaks after binary operators.
The preferred place to break around a binary operator is before the
operator, not after it.
W504: (width == 0 +\n height == 0)
W504: (width == 0 and\n height == 0)
W504: var = (1 &\n ~2)
Okay: foo(\n -x)
Okay: foo(x\n [])
Okay: x = '''\n''' + ''
Okay: x = '' + '''\n'''
Okay: foo(x,\n -y)
Okay: foo(x, # comment\n -y)
The following should be W504 but unary_context is tricky with these
Okay: var = (1 /\n -2)
Okay: var = (1 +\n -1 +\n -2)
"""
prev_start = None
for context in _break_around_binary_operators(tokens):
(token_type, text, previous_token_type, previous_text,
line_break, unary_context, start) = context
if (_is_binary_operator(previous_token_type, previous_text) and
line_break and
not unary_context and
not _is_binary_operator(token_type, text)):
yield prev_start, "W504 line break after binary operator"
prev_start = start | r""" Avoid breaks after binary operators. The preferred place to break around a binary operator is before the operator, not after it. W504: (width == 0 +\n height == 0) W504: (width == 0 and\n height == 0) W504: var = (1 &\n ~2) Okay: foo(\n -x) Okay: foo(x\n []) Okay: x = '''\n''' + '' Okay: x = '' + '''\n''' Okay: foo(x,\n -y) Okay: foo(x, # comment\n -y) The following should be W504 but unary_context is tricky with these Okay: var = (1 /\n -2) Okay: var = (1 +\n -1 +\n -2) |
177,051 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
COMPARE_SINGLETON_REGEX = re.compile(r'(\bNone|\bFalse|\bTrue)?\s*([=!]=)'
r'\s*(?(1)|(None|False|True))\b')
The provided code snippet includes necessary dependencies for implementing the `comparison_to_singleton` function. Write a Python function `def comparison_to_singleton(logical_line, noqa)` to solve the following problem:
r"""Comparison to singletons should use "is" or "is not". Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg: Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
Here is the function:
def comparison_to_singleton(logical_line, noqa):
r"""Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done
with "is" or "is not", never the equality operators.
Okay: if arg is not None:
E711: if arg != None:
E711: if None == arg:
E712: if arg == True:
E712: if False == arg:
Also, beware of writing if x when you really mean if x is not None
-- e.g. when testing whether a variable or argument that defaults to
None was set to some other value. The other value might have a type
(such as a container) that could be false in a boolean context!
"""
if noqa:
return
for match in COMPARE_SINGLETON_REGEX.finditer(logical_line):
singleton = match.group(1) or match.group(3)
same = (match.group(2) == '==')
msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
if singleton in ('None',):
code = 'E711'
else:
code = 'E712'
nonzero = ((singleton == 'True' and same) or
(singleton == 'False' and not same))
msg += " or 'if %scond:'" % ('' if nonzero else 'not ')
yield match.start(2), ("%s comparison to %s should be %s" %
(code, singleton, msg)) | r"""Comparison to singletons should use "is" or "is not". Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg: Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context! |
177,052 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
COMPARE_NEGATIVE_REGEX = re.compile(r'\b(?<!is\s)(not)\s+[^][)(}{ ]+\s+'
r'(in|is)\s')
The provided code snippet includes necessary dependencies for implementing the `comparison_negative` function. Write a Python function `def comparison_negative(logical_line)` to solve the following problem:
r"""Negative comparison should be done using "not in" and "is not". Okay: if x not in y:\n pass Okay: assert (X in Y or X is Z) Okay: if not (X in Y):\n pass Okay: zz = x is not y E713: Z = not X in Y E713: if not X.B in Y:\n pass E714: if not X is Y:\n pass E714: Z = not X.B is Y
Here is the function:
def comparison_negative(logical_line):
r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if not X is Y:\n pass
E714: Z = not X.B is Y
"""
match = COMPARE_NEGATIVE_REGEX.search(logical_line)
if match:
pos = match.start(1)
if match.group(2) == 'in':
yield pos, "E713 test for membership should be 'not in'"
else:
yield pos, "E714 test for object identity should be 'is not'" | r"""Negative comparison should be done using "not in" and "is not". Okay: if x not in y:\n pass Okay: assert (X in Y or X is Z) Okay: if not (X in Y):\n pass Okay: zz = x is not y E713: Z = not X in Y E713: if not X.B in Y:\n pass E714: if not X is Y:\n pass E714: Z = not X.B is Y |
177,053 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
SINGLETONS = frozenset(['False', 'None', 'True'])
COMPARE_TYPE_REGEX = re.compile(r'(?:[=!]=|is(?:\s+not)?)\s+type(?:s.\w+Type'
r'|\s*\(\s*([^)]*[^ )])\s*\))')
The provided code snippet includes necessary dependencies for implementing the `comparison_type` function. Write a Python function `def comparison_type(logical_line, noqa)` to solve the following problem:
r"""Object type comparisons should always use isinstance(). Do not compare types directly. Okay: if isinstance(obj, int): E721: if type(obj) is type(1): When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do: Okay: if isinstance(obj, basestring): Okay: if type(a1) is type(b1):
Here is the function:
def comparison_type(logical_line, noqa):
r"""Object type comparisons should always use isinstance().
Do not compare types directly.
Okay: if isinstance(obj, int):
E721: if type(obj) is type(1):
When checking if an object is a string, keep in mind that it might
be a unicode string too! In Python 2.3, str and unicode have a
common base class, basestring, so you can do:
Okay: if isinstance(obj, basestring):
Okay: if type(a1) is type(b1):
"""
match = COMPARE_TYPE_REGEX.search(logical_line)
if match and not noqa:
inst = match.group(1)
if inst and inst.isidentifier() and inst not in SINGLETONS:
return # Allow comparison for types which are not obvious
yield match.start(), "E721 do not compare types, use 'isinstance()'" | r"""Object type comparisons should always use isinstance(). Do not compare types directly. Okay: if isinstance(obj, int): E721: if type(obj) is type(1): When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do: Okay: if isinstance(obj, basestring): Okay: if type(a1) is type(b1): |
177,054 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
BLANK_EXCEPT_REGEX = re.compile(r"except\s*:")
The provided code snippet includes necessary dependencies for implementing the `bare_except` function. Write a Python function `def bare_except(logical_line, noqa)` to solve the following problem:
r"""When catching exceptions, mention specific exceptions when possible. Okay: except Exception: Okay: except BaseException: E722: except:
Here is the function:
def bare_except(logical_line, noqa):
r"""When catching exceptions, mention specific exceptions when
possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
"""
if noqa:
return
match = BLANK_EXCEPT_REGEX.match(logical_line)
if match:
yield match.start(), "E722 do not use bare 'except'" | r"""When catching exceptions, mention specific exceptions when possible. Okay: except Exception: Okay: except BaseException: E722: except: |
177,055 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `ambiguous_identifier` function. Write a Python function `def ambiguous_identifier(logical_line, tokens)` to solve the following problem:
r"""Never use the characters 'l', 'O', or 'I' as variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead. Okay: L = 0 Okay: o = 123 Okay: i = 42 E741: l = 0 E741: O = 123 E741: I = 42 Variables can be bound in several other contexts, including class and function definitions, lambda functions, 'global' and 'nonlocal' statements, exception handlers, and 'with' and 'for' statements. In addition, we have a special handling for function parameters. Okay: except AttributeError as o: Okay: with lock as L: Okay: foo(l=12) Okay: foo(l=I) Okay: for a in foo(l=12): Okay: lambda arg: arg * l Okay: lambda a=l[I:5]: None Okay: lambda x=a.I: None Okay: if l >= 12: E741: except AttributeError as O: E741: with lock as l: E741: global I E741: nonlocal l E741: def foo(l): E741: def foo(l=12): E741: l = foo(l=12) E741: for l in range(10): E741: [l for l in lines if l] E741: lambda l: None E741: lambda a=x[1:5], l: None E741: lambda **l: E741: def f(**l): E742: class I(object): E743: def l(x):
Here is the function:
def ambiguous_identifier(logical_line, tokens):
r"""Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the
numerals one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0
Okay: o = 123
Okay: i = 42
E741: l = 0
E741: O = 123
E741: I = 42
Variables can be bound in several other contexts, including class
and function definitions, lambda functions, 'global' and 'nonlocal'
statements, exception handlers, and 'with' and 'for' statements.
In addition, we have a special handling for function parameters.
Okay: except AttributeError as o:
Okay: with lock as L:
Okay: foo(l=12)
Okay: foo(l=I)
Okay: for a in foo(l=12):
Okay: lambda arg: arg * l
Okay: lambda a=l[I:5]: None
Okay: lambda x=a.I: None
Okay: if l >= 12:
E741: except AttributeError as O:
E741: with lock as l:
E741: global I
E741: nonlocal l
E741: def foo(l):
E741: def foo(l=12):
E741: l = foo(l=12)
E741: for l in range(10):
E741: [l for l in lines if l]
E741: lambda l: None
E741: lambda a=x[1:5], l: None
E741: lambda **l:
E741: def f(**l):
E742: class I(object):
E743: def l(x):
"""
func_depth = None # set to brace depth if 'def' or 'lambda' is found
seen_colon = False # set to true if we're done with function parameters
brace_depth = 0
idents_to_avoid = ('l', 'O', 'I')
prev_type, prev_text, prev_start, prev_end, __ = tokens[0]
for index in range(1, len(tokens)):
token_type, text, start, end, line = tokens[index]
ident = pos = None
# find function definitions
if prev_text in {'def', 'lambda'}:
func_depth = brace_depth
seen_colon = False
elif (
func_depth is not None and
text == ':' and
brace_depth == func_depth
):
seen_colon = True
# update parameter parentheses level
if text in '([{':
brace_depth += 1
elif text in ')]}':
brace_depth -= 1
# identifiers on the lhs of an assignment operator
if text == ':=' or (text == '=' and brace_depth == 0):
if prev_text in idents_to_avoid:
ident = prev_text
pos = prev_start
# identifiers bound to values with 'as', 'for',
# 'global', or 'nonlocal'
if prev_text in ('as', 'for', 'global', 'nonlocal'):
if text in idents_to_avoid:
ident = text
pos = start
# function / lambda parameter definitions
if (
func_depth is not None and
not seen_colon and
index < len(tokens) - 1 and tokens[index + 1][1] in ':,=)' and
prev_text in {'lambda', ',', '*', '**', '('} and
text in idents_to_avoid
):
ident = text
pos = start
if prev_text == 'class':
if text in idents_to_avoid:
yield start, "E742 ambiguous class definition '%s'" % text
if prev_text == 'def':
if text in idents_to_avoid:
yield start, "E743 ambiguous function definition '%s'" % text
if ident:
yield pos, "E741 ambiguous variable name '%s'" % ident
prev_text = text
prev_start = start | r"""Never use the characters 'l', 'O', or 'I' as variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead. Okay: L = 0 Okay: o = 123 Okay: i = 42 E741: l = 0 E741: O = 123 E741: I = 42 Variables can be bound in several other contexts, including class and function definitions, lambda functions, 'global' and 'nonlocal' statements, exception handlers, and 'with' and 'for' statements. In addition, we have a special handling for function parameters. Okay: except AttributeError as o: Okay: with lock as L: Okay: foo(l=12) Okay: foo(l=I) Okay: for a in foo(l=12): Okay: lambda arg: arg * l Okay: lambda a=l[I:5]: None Okay: lambda x=a.I: None Okay: if l >= 12: E741: except AttributeError as O: E741: with lock as l: E741: global I E741: nonlocal l E741: def foo(l): E741: def foo(l=12): E741: l = foo(l=12) E741: for l in range(10): E741: [l for l in lines if l] E741: lambda l: None E741: lambda a=x[1:5], l: None E741: lambda **l: E741: def f(**l): E742: class I(object): E743: def l(x): |
177,056 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `python_3000_invalid_escape_sequence` function. Write a Python function `def python_3000_invalid_escape_sequence(logical_line, tokens, noqa)` to solve the following problem:
r"""Invalid escape sequences are deprecated in Python 3.6. Okay: regex = r'\.png$' W605: regex = '\.png$'
Here is the function:
def python_3000_invalid_escape_sequence(logical_line, tokens, noqa):
r"""Invalid escape sequences are deprecated in Python 3.6.
Okay: regex = r'\.png$'
W605: regex = '\.png$'
"""
if noqa:
return
# https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
valid = [
'\n',
'\\',
'\'',
'"',
'a',
'b',
'f',
'n',
'r',
't',
'v',
'0', '1', '2', '3', '4', '5', '6', '7',
'x',
# Escape sequences only recognized in string literals
'N',
'u',
'U',
]
for token_type, text, start, end, line in tokens:
if token_type == tokenize.STRING:
start_line, start_col = start
quote = text[-3:] if text[-3:] in ('"""', "'''") else text[-1]
# Extract string modifiers (e.g. u or r)
quote_pos = text.index(quote)
prefix = text[:quote_pos].lower()
start = quote_pos + len(quote)
string = text[start:-len(quote)]
if 'r' not in prefix:
pos = string.find('\\')
while pos >= 0:
pos += 1
if string[pos] not in valid:
line = start_line + string.count('\n', 0, pos)
if line == start_line:
col = start_col + len(prefix) + len(quote) + pos
else:
col = pos - string.rfind('\n', 0, pos) - 1
yield (
(line, col - 1),
"W605 invalid escape sequence '\\%s'" %
string[pos],
)
pos = string.find('\\', pos + 1) | r"""Invalid escape sequences are deprecated in Python 3.6. Okay: regex = r'\.png$' W605: regex = '\.png$' |
177,057 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `python_3000_async_await_keywords` function. Write a Python function `def python_3000_async_await_keywords(logical_line, tokens)` to solve the following problem:
async' and 'await' are reserved keywords starting at Python 3.7. W606: async = 42 W606: await = 42 Okay: async def read(db):\n data = await db.fetch('SELECT ...')
Here is the function:
def python_3000_async_await_keywords(logical_line, tokens):
"""'async' and 'await' are reserved keywords starting at Python 3.7.
W606: async = 42
W606: await = 42
Okay: async def read(db):\n data = await db.fetch('SELECT ...')
"""
# The Python tokenize library before Python 3.5 recognizes
# async/await as a NAME token. Therefore, use a state machine to
# look for the possible async/await constructs as defined by the
# Python grammar:
# https://docs.python.org/3/reference/grammar.html
state = None
for token_type, text, start, end, line in tokens:
error = False
if token_type == tokenize.NL:
continue
if state is None:
if token_type == tokenize.NAME:
if text == 'async':
state = ('async_stmt', start)
elif text == 'await':
state = ('await', start)
elif (token_type == tokenize.NAME and
text in ('def', 'for')):
state = ('define', start)
elif state[0] == 'async_stmt':
if token_type == tokenize.NAME and text in ('def', 'with', 'for'):
# One of funcdef, with_stmt, or for_stmt. Return to
# looking for async/await names.
state = None
else:
error = True
elif state[0] == 'await':
if token_type == tokenize.NAME:
# An await expression. Return to looking for async/await
# names.
state = None
elif token_type == tokenize.OP and text == '(':
state = None
else:
error = True
elif state[0] == 'define':
if token_type == tokenize.NAME and text in ('async', 'await'):
error = True
else:
state = None
if error:
yield (
state[1],
"W606 'async' and 'await' are reserved keywords starting with "
"Python 3.7",
)
state = None
# Last token
if state is not None:
yield (
state[1],
"W606 'async' and 'await' are reserved keywords starting with "
"Python 3.7",
) | async' and 'await' are reserved keywords starting at Python 3.7. W606: async = 42 W606: await = 42 Okay: async def read(db):\n data = await db.fetch('SELECT ...') |
177,058 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
MAX_DOC_LENGTH = 72
SKIP_TOKENS = NEWLINE.union([tokenize.INDENT, tokenize.DEDENT])
SKIP_COMMENTS = SKIP_TOKENS.union([tokenize.COMMENT, tokenize.ERRORTOKEN])
The provided code snippet includes necessary dependencies for implementing the `maximum_doc_length` function. Write a Python function `def maximum_doc_length(logical_line, max_doc_length, noqa, tokens)` to solve the following problem:
r"""Limit all doc lines to a maximum of 72 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. Reports warning W505
Here is the function:
def maximum_doc_length(logical_line, max_doc_length, noqa, tokens):
r"""Limit all doc lines to a maximum of 72 characters.
For flowing long blocks of text (docstrings or comments), limiting
the length to 72 characters is recommended.
Reports warning W505
"""
if max_doc_length is None or noqa:
return
prev_token = None
skip_lines = set()
# Skip lines that
for token_type, text, start, end, line in tokens:
if token_type not in SKIP_COMMENTS.union([tokenize.STRING]):
skip_lines.add(line)
for token_type, text, start, end, line in tokens:
# Skip lines that aren't pure strings
if token_type == tokenize.STRING and skip_lines:
continue
if token_type in (tokenize.STRING, tokenize.COMMENT):
# Only check comment-only lines
if prev_token is None or prev_token in SKIP_TOKENS:
lines = line.splitlines()
for line_num, physical_line in enumerate(lines):
if start[0] + line_num == 1 and line.startswith('#!'):
return
length = len(physical_line)
chunks = physical_line.split()
if token_type == tokenize.COMMENT:
if (len(chunks) == 2 and
length - len(chunks[-1]) < MAX_DOC_LENGTH):
continue
if len(chunks) == 1 and line_num + 1 < len(lines):
if (len(chunks) == 1 and
length - len(chunks[-1]) < MAX_DOC_LENGTH):
continue
if length > max_doc_length:
doc_error = (start[0] + line_num, max_doc_length)
yield (doc_error, "W505 doc line too long "
"(%d > %d characters)"
% (length, max_doc_length))
prev_token = token_type | r"""Limit all doc lines to a maximum of 72 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. Reports warning W505 |
177,059 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
The provided code snippet includes necessary dependencies for implementing the `mute_string` function. Write a Python function `def mute_string(text)` to solve the following problem:
Replace contents with 'xxx' to prevent syntax matching. >>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'"
Here is the function:
def mute_string(text):
"""Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"')
'"xxx"'
>>> mute_string("'''abc'''")
"'''xxx'''"
>>> mute_string("r'abc'")
"r'xxx'"
"""
# String modifiers (e.g. u or r)
start = text.index(text[-1]) + 1
end = len(text) - 1
# Triple quotes
if text[-3:] in ('"""', "'''"):
start += 2
end -= 2
return text[:start] + 'x' * (end - start) + text[end:] | Replace contents with 'xxx' to prevent syntax matching. >>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'" |
177,060 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE])
def _is_eol_token(token):
return token[0] in NEWLINE or token[4][token[3][1]:].lstrip() == '\\\n' | null |
177,061 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
PROJECT_CONFIG = ('setup.cfg', 'tox.ini')
def stdin_get_value():
"""Read the value from stdin."""
return io.TextIOWrapper(sys.stdin.buffer, errors='ignore').read()
def parse_udiff(diff, patterns=None, parent='.'):
"""Return a dictionary of matching lines."""
# For each file of the diff, the entry key is the filename,
# and the value is a set of row numbers to consider.
rv = {}
path = nrows = None
for line in diff.splitlines():
if nrows:
if line[:1] != '-':
nrows -= 1
continue
if line[:3] == '@@ ':
hunk_match = HUNK_REGEX.match(line)
(row, nrows) = (int(g or '1') for g in hunk_match.groups())
rv[path].update(range(row, row + nrows))
elif line[:3] == '+++':
path = line[4:].split('\t', 1)[0]
# Git diff will use (i)ndex, (w)ork tree, (c)ommit and
# (o)bject instead of a/b/c/d as prefixes for patches
if path[:2] in ('b/', 'w/', 'i/'):
path = path[2:]
rv[path] = set()
return {
os.path.join(parent, filepath): rows
for (filepath, rows) in rv.items()
if rows and filename_match(filepath, patterns)
}
def normalize_paths(value, parent=os.curdir):
"""Parse a comma-separated list of paths.
Return a list of absolute paths.
"""
if not value:
return []
if isinstance(value, list):
return value
paths = []
for path in value.split(','):
path = path.strip()
if '/' in path:
path = os.path.abspath(os.path.join(parent, path))
paths.append(path.rstrip('/'))
return paths
class FileReport(BaseReport):
"""Collect the results of the checks and print the filenames."""
print_filename = True
class DiffReport(StandardReport):
"""Collect and print the results for the changed lines only."""
def __init__(self, options):
super().__init__(options)
self._selected = options.selected_lines
def error(self, line_number, offset, text, check):
if line_number not in self._selected[self.filename]:
return
return super().error(line_number, offset, text, check)
def get_parser(prog='pycodestyle', version=__version__):
"""Create the parser for the program."""
parser = OptionParser(prog=prog, version=version,
usage="%prog [options] input ...")
parser.config_options = [
'exclude', 'filename', 'select', 'ignore', 'max-line-length',
'max-doc-length', 'indent-size', 'hang-closing', 'count', 'format',
'quiet', 'show-pep8', 'show-source', 'statistics', 'verbose']
parser.add_option('-v', '--verbose', default=0, action='count',
help="print status messages, or debug with -vv")
parser.add_option('-q', '--quiet', default=0, action='count',
help="report only file names, or nothing with -qq")
parser.add_option('-r', '--repeat', default=True, action='store_true',
help="(obsolete) show all occurrences of the same error")
parser.add_option('--first', action='store_false', dest='repeat',
help="show first occurrence of each error")
parser.add_option('--exclude', metavar='patterns', default=DEFAULT_EXCLUDE,
help="exclude files or directories which match these "
"comma separated patterns (default: %default)")
parser.add_option('--filename', metavar='patterns', default='*.py',
help="when parsing directories, only check filenames "
"matching these comma separated patterns "
"(default: %default)")
parser.add_option('--select', metavar='errors', default='',
help="select errors and warnings (e.g. E,W6)")
parser.add_option('--ignore', metavar='errors', default='',
help="skip errors and warnings (e.g. E4,W) "
"(default: %s)" % DEFAULT_IGNORE)
parser.add_option('--show-source', action='store_true',
help="show source code for each error")
parser.add_option('--show-pep8', action='store_true',
help="show text of PEP 8 for each error "
"(implies --first)")
parser.add_option('--statistics', action='store_true',
help="count errors and warnings")
parser.add_option('--count', action='store_true',
help="print total number of errors and warnings "
"to standard error and set exit code to 1 if "
"total is not null")
parser.add_option('--max-line-length', type='int', metavar='n',
default=MAX_LINE_LENGTH,
help="set maximum allowed line length "
"(default: %default)")
parser.add_option('--max-doc-length', type='int', metavar='n',
default=None,
help="set maximum allowed doc line length and perform "
"these checks (unchecked if not set)")
parser.add_option('--indent-size', type='int', metavar='n',
default=INDENT_SIZE,
help="set how many spaces make up an indent "
"(default: %default)")
parser.add_option('--hang-closing', action='store_true',
help="hang closing bracket instead of matching "
"indentation of opening bracket's line")
parser.add_option('--format', metavar='format', default='default',
help="set the error format [default|pylint|<custom>]")
parser.add_option('--diff', action='store_true',
help="report changes only within line number ranges in "
"the unified diff received on STDIN")
group = parser.add_option_group("Testing Options")
if os.path.exists(TESTSUITE_PATH):
group.add_option('--testsuite', metavar='dir',
help="run regression tests from dir")
group.add_option('--doctest', action='store_true',
help="run doctest on myself")
group.add_option('--benchmark', action='store_true',
help="measure processing speed")
return parser
def read_config(options, args, arglist, parser):
"""Read and parse configurations.
If a config file is specified on the command line with the
"--config" option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any
local configurations in the current directory or above will be
merged together (in that order) using the read method of
ConfigParser.
"""
config = configparser.RawConfigParser()
cli_conf = options.config
local_dir = os.curdir
if USER_CONFIG and os.path.isfile(USER_CONFIG):
if options.verbose:
print('user configuration: %s' % USER_CONFIG)
config.read(USER_CONFIG)
parent = tail = args and os.path.abspath(os.path.commonprefix(args))
while tail:
if config.read(os.path.join(parent, fn) for fn in PROJECT_CONFIG):
local_dir = parent
if options.verbose:
print('local configuration: in %s' % parent)
break
(parent, tail) = os.path.split(parent)
if cli_conf and os.path.isfile(cli_conf):
if options.verbose:
print('cli configuration: %s' % cli_conf)
config.read(cli_conf)
pycodestyle_section = None
if config.has_section(parser.prog):
pycodestyle_section = parser.prog
elif config.has_section('pep8'):
pycodestyle_section = 'pep8' # Deprecated
warnings.warn('[pep8] section is deprecated. Use [pycodestyle].')
if pycodestyle_section:
option_list = {o.dest: o.type or o.action for o in parser.option_list}
# First, read the default values
(new_options, __) = parser.parse_args([])
# Second, parse the configuration
for opt in config.options(pycodestyle_section):
if opt.replace('_', '-') not in parser.config_options:
print(" unknown option '%s' ignored" % opt)
continue
if options.verbose > 1:
print(" {} = {}".format(opt,
config.get(pycodestyle_section, opt)))
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
if opt_type in ('int', 'count'):
value = config.getint(pycodestyle_section, opt)
elif opt_type in ('store_true', 'store_false'):
value = config.getboolean(pycodestyle_section, opt)
else:
value = config.get(pycodestyle_section, opt)
if normalized_opt == 'exclude':
value = normalize_paths(value, local_dir)
setattr(new_options, normalized_opt, value)
# Third, overwrite with the command-line options
(options, __) = parser.parse_args(arglist, values=new_options)
options.doctest = options.testsuite = False
return options
def _parse_multi_options(options, split_token=','):
r"""Split and strip and discard empties.
Turns the following:
A,
B,
into ["A", "B"]
"""
if options:
return [o.strip() for o in options.split(split_token) if o.strip()]
else:
return options
The provided code snippet includes necessary dependencies for implementing the `process_options` function. Write a Python function `def process_options(arglist=None, parse_argv=False, config_file=None, parser=None, verbose=None)` to solve the following problem:
Process options passed either via arglist or command line args. Passing in the ``config_file`` parameter allows other tools, such as flake8 to specify their own options to be processed in pycodestyle.
Here is the function:
def process_options(arglist=None, parse_argv=False, config_file=None,
parser=None, verbose=None):
"""Process options passed either via arglist or command line args.
Passing in the ``config_file`` parameter allows other tools, such as
flake8 to specify their own options to be processed in pycodestyle.
"""
if not parser:
parser = get_parser()
if not parser.has_option('--config'):
group = parser.add_option_group("Configuration", description=(
"The project options are read from the [%s] section of the "
"tox.ini file or the setup.cfg file located in any parent folder "
"of the path(s) being processed. Allowed options are: %s." %
(parser.prog, ', '.join(parser.config_options))))
group.add_option('--config', metavar='path', default=config_file,
help="user config file location")
# Don't read the command line if the module is used as a library.
if not arglist and not parse_argv:
arglist = []
# If parse_argv is True and arglist is None, arguments are
# parsed from the command line (sys.argv)
(options, args) = parser.parse_args(arglist)
options.reporter = None
# If explicitly specified verbosity, override any `-v` CLI flag
if verbose is not None:
options.verbose = verbose
if options.ensure_value('testsuite', False):
args.append(options.testsuite)
elif not options.ensure_value('doctest', False):
if parse_argv and not args:
if options.diff or any(os.path.exists(name)
for name in PROJECT_CONFIG):
args = ['.']
else:
parser.error('input not specified')
options = read_config(options, args, arglist, parser)
options.reporter = parse_argv and options.quiet == 1 and FileReport
options.filename = _parse_multi_options(options.filename)
options.exclude = normalize_paths(options.exclude)
options.select = _parse_multi_options(options.select)
options.ignore = _parse_multi_options(options.ignore)
if options.diff:
options.reporter = DiffReport
stdin = stdin_get_value()
options.selected_lines = parse_udiff(stdin, options.filename, args[0])
args = sorted(options.selected_lines)
return options, args | Process options passed either via arglist or command line args. Passing in the ``config_file`` parameter allows other tools, such as flake8 to specify their own options to be processed in pycodestyle. |
177,062 | import bisect
import configparser
import inspect
import io
import keyword
import os
import re
import sys
import time
import tokenize
import warnings
from fnmatch import fnmatch
from functools import lru_cache
from optparse import OptionParser
if (
sys.version_info < (3, 10) and
callable(getattr(tokenize, '_compile', None))
): # pragma: no cover (<py310)
tokenize._compile = lru_cache()(tokenize._compile) # type: ignore
try:
if sys.platform == 'win32':
USER_CONFIG = os.path.expanduser(r'~\.pycodestyle')
else:
USER_CONFIG = os.path.join(
os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
'pycodestyle'
)
except ImportError:
USER_CONFIG = None
class StyleGuide:
"""Initialize a PEP-8 instance with few options."""
def __init__(self, *args, **kwargs):
# build options from the command line
self.checker_class = kwargs.pop('checker_class', Checker)
parse_argv = kwargs.pop('parse_argv', False)
config_file = kwargs.pop('config_file', False)
parser = kwargs.pop('parser', None)
# build options from dict
options_dict = dict(*args, **kwargs)
arglist = None if parse_argv else options_dict.get('paths', None)
verbose = options_dict.get('verbose', None)
options, self.paths = process_options(
arglist, parse_argv, config_file, parser, verbose)
if options_dict:
options.__dict__.update(options_dict)
if 'paths' in options_dict:
self.paths = options_dict['paths']
self.runner = self.input_file
self.options = options
if not options.reporter:
options.reporter = BaseReport if options.quiet else StandardReport
options.select = tuple(options.select or ())
if not (options.select or options.ignore or
options.testsuite or options.doctest) and DEFAULT_IGNORE:
# The default choice: ignore controversial checks
options.ignore = tuple(DEFAULT_IGNORE.split(','))
else:
# Ignore all checks which are not explicitly selected
options.ignore = ('',) if options.select else tuple(options.ignore)
options.benchmark_keys = BENCHMARK_KEYS[:]
options.ignore_code = self.ignore_code
options.physical_checks = self.get_checks('physical_line')
options.logical_checks = self.get_checks('logical_line')
options.ast_checks = self.get_checks('tree')
self.init_report()
def init_report(self, reporter=None):
"""Initialize the report instance."""
self.options.report = (reporter or self.options.reporter)(self.options)
return self.options.report
def check_files(self, paths=None):
"""Run all checks on the paths."""
if paths is None:
paths = self.paths
report = self.options.report
runner = self.runner
report.start()
try:
for path in paths:
if os.path.isdir(path):
self.input_dir(path)
elif not self.excluded(path):
runner(path)
except KeyboardInterrupt:
print('... stopped')
report.stop()
return report
def input_file(self, filename, lines=None, expected=None, line_offset=0):
"""Run all checks on a Python source file."""
if self.options.verbose:
print('checking %s' % filename)
fchecker = self.checker_class(
filename, lines=lines, options=self.options)
return fchecker.check_all(expected=expected, line_offset=line_offset)
def input_dir(self, dirname):
"""Check all files in this directory and all subdirectories."""
dirname = dirname.rstrip('/')
if self.excluded(dirname):
return 0
counters = self.options.report.counters
verbose = self.options.verbose
filepatterns = self.options.filename
runner = self.runner
for root, dirs, files in os.walk(dirname):
if verbose:
print('directory ' + root)
counters['directories'] += 1
for subdir in sorted(dirs):
if self.excluded(subdir, root):
dirs.remove(subdir)
for filename in sorted(files):
# contain a pattern that matches?
if (
filename_match(filename, filepatterns) and
not self.excluded(filename, root)
):
runner(os.path.join(root, filename))
def excluded(self, filename, parent=None):
"""Check if the file should be excluded.
Check if 'options.exclude' contains a pattern matching filename.
"""
if not self.options.exclude:
return False
basename = os.path.basename(filename)
if filename_match(basename, self.options.exclude):
return True
if parent:
filename = os.path.join(parent, filename)
filename = os.path.abspath(filename)
return filename_match(filename, self.options.exclude)
def ignore_code(self, code):
"""Check if the error code should be ignored.
If 'options.select' contains a prefix of the error code,
return False. Else, if 'options.ignore' contains a prefix of
the error code, return True.
"""
if len(code) < 4 and any(s.startswith(code)
for s in self.options.select):
return False
return (code.startswith(self.options.ignore) and
not code.startswith(self.options.select))
def get_checks(self, argument_name):
"""Get all the checks for this category.
Find all globally visible functions where the first argument
name starts with argument_name and which contain selected tests.
"""
checks = []
for check, attrs in _checks[argument_name].items():
(codes, args) = attrs
if any(not (code and self.ignore_code(code)) for code in codes):
checks.append((check.__name__, check, args))
return sorted(checks)
The provided code snippet includes necessary dependencies for implementing the `_main` function. Write a Python function `def _main()` to solve the following problem:
Parse options and run checks on Python source.
Here is the function:
def _main():
"""Parse options and run checks on Python source."""
import signal
# Handle "Broken pipe" gracefully
try:
signal.signal(signal.SIGPIPE, lambda signum, frame: sys.exit(1))
except AttributeError:
pass # not supported on Windows
style_guide = StyleGuide(parse_argv=True)
options = style_guide.options
if options.doctest or options.testsuite:
from testsuite.support import run_tests
report = run_tests(style_guide)
else:
report = style_guide.check_files()
if options.statistics:
report.print_statistics()
if options.benchmark:
report.print_benchmark()
if options.testsuite and not options.quiet:
report.print_results()
if report.total_errors:
if options.count:
sys.stderr.write(str(report.total_errors) + '\n')
sys.exit(1) | Parse options and run checks on Python source. |
177,063 | import contextlib
import os
def _iter_files(dirname, subdirs, prune_dir, exclude_file):
for basename in os.listdir(dirname):
filename = os.path.join(dirname, basename)
if os.path.isdir(filename):
if prune_dir is not None and prune_dir(dirname, basename):
continue
subdirs.append(filename)
else:
# TODO: Use os.path.isfile() to narrow it down?
if exclude_file is not None and exclude_file(dirname, basename):
continue
yield dirname, basename, filename
The provided code snippet includes necessary dependencies for implementing the `iter_tree` function. Write a Python function `def iter_tree(root, prune_dir=None, exclude_file=None)` to solve the following problem:
Yield (dirname, files) for each directory in the tree. The list of files is actually a list of (basename, filename). This is an alternative to os.walk() with filtering.
Here is the function:
def iter_tree(root, prune_dir=None, exclude_file=None):
"""Yield (dirname, files) for each directory in the tree.
The list of files is actually a list of (basename, filename).
This is an alternative to os.walk() with filtering."""
pending = [root]
while pending:
dirname = pending.pop(0)
files = []
for _, b, f in _iter_files(dirname, pending, prune_dir, exclude_file):
files.append((b, f))
yield dirname, files | Yield (dirname, files) for each directory in the tree. The list of files is actually a list of (basename, filename). This is an alternative to os.walk() with filtering. |
177,064 | from importlib import import_module
import os
import warnings
from . import check_modules, prefix_matcher, preimport, vendored
import pydevd
import debugpy
from _pydevd_bundle import pydevd_constants
from _pydevd_bundle import pydevd_defaults
def debugpy_breakpointhook():
debugpy.breakpoint() | null |
177,065 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
os_path_exists = os.path.exists
if sys.platform == 'win32':
try:
import ctypes
from ctypes.wintypes import MAX_PATH, LPCWSTR, LPWSTR, DWORD
GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW # noqa
GetLongPathName.argtypes = [LPCWSTR, LPWSTR, DWORD]
GetLongPathName.restype = DWORD
GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW # noqa
GetShortPathName.argtypes = [LPCWSTR, LPWSTR, DWORD]
GetShortPathName.restype = DWORD
# Check that it actually works
_get_path_with_real_case(__file__)
except:
# Something didn't quite work out, leave no-op conversions in place.
if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2:
pydev_log.exception()
else:
convert_to_long_pathname = _convert_to_long_pathname
convert_to_short_pathname = _convert_to_short_pathname
get_path_with_real_case = _get_path_with_real_case
elif IS_JYTHON and IS_WINDOWS:
elif IS_MAC:
def basename(filename):
'''
Provides the basename for a file.
'''
return get_abs_path_real_path_and_base_from_file(filename)[2]
def _get_library_dir():
library_dir = None
try:
import sysconfig
library_dir = sysconfig.get_path('purelib')
except ImportError:
pass # i.e.: Only 2.7 onwards
if library_dir is None or not os_path_exists(library_dir):
for path in sys.path:
if os_path_exists(path) and os.path.basename(path) == 'site-packages':
library_dir = path
break
if library_dir is None or not os_path_exists(library_dir):
library_dir = os.path.dirname(os.__file__)
return library_dir | null |
177,066 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
def _convert_to_long_pathname(filename):
buf = ctypes.create_unicode_buffer(MAX_PATH)
rv = GetLongPathName(filename, buf, MAX_PATH)
if rv != 0 and rv <= MAX_PATH:
filename = buf.value
return filename | null |
177,067 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
def _convert_to_short_pathname(filename):
buf = ctypes.create_unicode_buffer(MAX_PATH)
rv = GetShortPathName(filename, buf, MAX_PATH)
if rv != 0 and rv <= MAX_PATH:
filename = buf.value
return filename | null |
177,068 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
os_path_exists = os.path.exists
convert_to_long_pathname = lambda filename:filename
def _resolve_listing_parts(resolved, parts_in_lowercase, filename):
try:
if parts_in_lowercase == ['']:
return resolved
return _resolve_listing(resolved, iter(parts_in_lowercase))
except FileNotFoundError:
_listdir_cache.clear()
# Retry once after clearing the cache we have.
try:
return _resolve_listing(resolved, iter(parts_in_lowercase))
except FileNotFoundError:
if os_path_exists(filename):
# This is really strange, ask the user to report as error.
pydev_log.critical(
'pydev debugger: critical: unable to get real case for file. Details:\n'
'filename: %s\ndrive: %s\nparts: %s\n'
'(please create a ticket in the tracker to address this).',
filename, resolved, parts_in_lowercase
)
pydev_log.exception()
# Don't fail, just return the original file passed.
return filename
except OSError:
# Something as: PermissionError (listdir may fail).
# See: https://github.com/microsoft/debugpy/issues/1154
# Don't fail nor log unless the trace level is at least info. Just return the original file passed.
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
pydev_log.info(
'pydev debugger: OSError: Unable to get real case for file. Details:\n'
'filename: %s\ndrive: %s\nparts: %s\n',
filename, resolved, parts_in_lowercase
)
pydev_log.exception()
return filename
def _get_path_with_real_case(filename):
# Note: this previously made:
# convert_to_long_pathname(convert_to_short_pathname(filename))
# but this is no longer done because we can't rely on getting the shortname
# consistently (there are settings to disable it on Windows).
# So, using approach which resolves by listing the dir.
if '~' in filename:
filename = convert_to_long_pathname(filename)
if filename.startswith('<') or not os_path_exists(filename):
return filename # Not much we can do.
drive, parts = os.path.splitdrive(os.path.normpath(filename))
drive = drive.upper()
while parts.startswith(os.path.sep):
parts = parts[1:]
drive += os.path.sep
parts = parts.lower().split(os.path.sep)
return _resolve_listing_parts(drive, parts, filename) | null |
177,069 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
_normcase_from_client = normcase
def normcase_from_client(s):
return _normcase_from_client(s) | null |
177,070 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
if IS_JYTHON:
def _normcase_windows(filename):
return filename.lower()
else:
def _normcase_windows(filename):
# `normcase` doesn't lower case on Python 2 for non-English locale, so we should do it manually.
if '~' in filename:
filename = convert_to_long_pathname(filename)
filename = _nt_os_normcase(filename)
return filename.lower()
def _normcase_linux(filename):
return filename # no-op
def normcase(s, NORMCASE_CACHE={}):
try:
return NORMCASE_CACHE[s]
except:
normalized = NORMCASE_CACHE[s] = _default_normcase(s)
return normalized
_ide_os = 'WINDOWS' if IS_WINDOWS else 'UNIX'
_normcase_from_client = normcase
DEBUG_CLIENT_SERVER_TRANSLATION = os.environ.get('DEBUG_PYDEVD_PATHS_TRANSLATION', 'False').lower() in ('1', 'true')
_last_client_server_paths_set = []
def setup_client_server_paths(paths):
'''paths is the same format as PATHS_FROM_ECLIPSE_TO_PYTHON'''
global map_file_to_client
global map_file_to_server
global _last_client_server_paths_set
global _next_source_reference
_last_client_server_paths_set = paths[:]
_source_reference_to_server_filename.clear()
_client_filename_in_utf8_to_source_reference.clear()
_next_source_reference = partial(next, itertools.count(1))
# Work on the client and server slashes.
python_sep = '\\' if IS_WINDOWS else '/'
eclipse_sep = '\\' if _ide_os == 'WINDOWS' else '/'
norm_filename_to_server_container = {}
norm_filename_to_client_container = {}
initial_paths = []
initial_paths_with_end_sep = []
paths_from_eclipse_to_python = []
paths_from_eclipse_to_python_with_end_sep = []
# Apply normcase to the existing paths to follow the os preferences.
for i, (path0, path1) in enumerate(paths):
force_only_slash = path0.endswith(('/', '\\')) and path1.endswith(('/', '\\'))
if not force_only_slash:
path0 = _fix_path(path0, eclipse_sep, False)
path1 = _fix_path(path1, python_sep, False)
initial_paths.append((path0, path1))
paths_from_eclipse_to_python.append((_normcase_from_client(path0), normcase(path1)))
# Now, make a version with a slash in the end.
path0 = _fix_path(path0, eclipse_sep, True)
path1 = _fix_path(path1, python_sep, True)
initial_paths_with_end_sep.append((path0, path1))
paths_from_eclipse_to_python_with_end_sep.append((_normcase_from_client(path0), normcase(path1)))
# Fix things so that we always match the versions with a slash in the end first.
initial_paths = initial_paths_with_end_sep + initial_paths
paths_from_eclipse_to_python = paths_from_eclipse_to_python_with_end_sep + paths_from_eclipse_to_python
if not paths_from_eclipse_to_python:
# no translation step needed (just inline the calls)
map_file_to_client = _original_file_to_client
map_file_to_server = _original_map_file_to_server
return
# only setup translation functions if absolutely needed!
def _map_file_to_server(filename, cache=norm_filename_to_server_container):
# Eclipse will send the passed filename to be translated to the python process
# So, this would be 'NormFileFromEclipseToPython'
try:
return cache[filename]
except KeyError:
if eclipse_sep != python_sep:
# Make sure that the separators are what we expect from the IDE.
filename = filename.replace(python_sep, eclipse_sep)
# used to translate a path from the client to the debug server
translated = filename
translated_normalized = _normcase_from_client(filename)
for eclipse_prefix, server_prefix in paths_from_eclipse_to_python:
if translated_normalized.startswith(eclipse_prefix):
found_translation = True
if DEBUG_CLIENT_SERVER_TRANSLATION:
pydev_log.critical('pydev debugger: replacing to server: %s', filename)
translated = server_prefix + filename[len(eclipse_prefix):]
if DEBUG_CLIENT_SERVER_TRANSLATION:
pydev_log.critical('pydev debugger: sent to server: %s - matched prefix: %s', translated, eclipse_prefix)
break
else:
found_translation = False
# Note that when going to the server, we do the replace first and only later do the norm file.
if eclipse_sep != python_sep:
translated = translated.replace(eclipse_sep, python_sep)
if found_translation:
# Note: we don't normalize it here, this must be done as a separate
# step by the caller.
translated = absolute_path(translated)
else:
if not os_path_exists(translated):
if not translated.startswith('<'):
# This is a configuration error, so, write it always so
# that the user can fix it.
error_once('pydev debugger: unable to find translation for: "%s" in [%s] (please revise your path mappings).\n',
filename, ', '.join(['"%s"' % (x[0],) for x in paths_from_eclipse_to_python]))
else:
# It's possible that we had some round trip (say, we sent /usr/lib and received
# it back, so, having no translation is ok too).
# Note: we don't normalize it here, this must be done as a separate
# step by the caller.
translated = absolute_path(translated)
cache[filename] = translated
return translated
def _map_file_to_client(filename, cache=norm_filename_to_client_container):
# The result of this method will be passed to eclipse
# So, this would be 'NormFileFromPythonToEclipse'
try:
return cache[filename]
except KeyError:
abs_path = absolute_path(filename)
translated_proper_case = get_path_with_real_case(abs_path)
translated_normalized = normcase(abs_path)
path_mapping_applied = False
if translated_normalized.lower() != translated_proper_case.lower():
if DEBUG_CLIENT_SERVER_TRANSLATION:
pydev_log.critical(
'pydev debugger: translated_normalized changed path (from: %s to %s)',
translated_proper_case, translated_normalized)
for i, (eclipse_prefix, python_prefix) in enumerate(paths_from_eclipse_to_python):
if translated_normalized.startswith(python_prefix):
if DEBUG_CLIENT_SERVER_TRANSLATION:
pydev_log.critical('pydev debugger: replacing to client: %s', translated_normalized)
# Note: use the non-normalized version.
eclipse_prefix = initial_paths[i][0]
translated = eclipse_prefix + translated_proper_case[len(python_prefix):]
if DEBUG_CLIENT_SERVER_TRANSLATION:
pydev_log.critical('pydev debugger: sent to client: %s - matched prefix: %s', translated, python_prefix)
path_mapping_applied = True
break
else:
if DEBUG_CLIENT_SERVER_TRANSLATION:
pydev_log.critical('pydev debugger: to client: unable to find matching prefix for: %s in %s',
translated_normalized, [x[1] for x in paths_from_eclipse_to_python])
translated = translated_proper_case
if eclipse_sep != python_sep:
translated = translated.replace(python_sep, eclipse_sep)
translated = _path_to_expected_str(translated)
# The resulting path is not in the python process, so, we cannot do a normalize the path here,
# only at the beginning of this method.
cache[filename] = (translated, path_mapping_applied)
if translated not in _client_filename_in_utf8_to_source_reference:
if path_mapping_applied:
source_reference = 0
else:
source_reference = _next_source_reference()
pydev_log.debug('Created source reference: %s for untranslated path: %s', source_reference, filename)
_client_filename_in_utf8_to_source_reference[translated] = source_reference
_source_reference_to_server_filename[source_reference] = filename
return (translated, path_mapping_applied)
map_file_to_server = _map_file_to_server
map_file_to_client = _map_file_to_client
setup_client_server_paths(PATHS_FROM_ECLIPSE_TO_PYTHON)
IS_WINDOWS = sys.platform == 'win32'
The provided code snippet includes necessary dependencies for implementing the `set_ide_os` function. Write a Python function `def set_ide_os(os)` to solve the following problem:
We need to set the IDE os because the host where the code is running may be actually different from the client (and the point is that we want the proper paths to translate from the client to the server). :param os: 'UNIX' or 'WINDOWS'
Here is the function:
def set_ide_os(os):
'''
We need to set the IDE os because the host where the code is running may be
actually different from the client (and the point is that we want the proper
paths to translate from the client to the server).
:param os:
'UNIX' or 'WINDOWS'
'''
global _ide_os
global _normcase_from_client
prev = _ide_os
if os == 'WIN': # Apparently PyCharm uses 'WIN' (https://github.com/fabioz/PyDev.Debugger/issues/116)
os = 'WINDOWS'
assert os in ('WINDOWS', 'UNIX')
if DEBUG_CLIENT_SERVER_TRANSLATION:
print('pydev debugger: client OS: %s' % (os,))
_normcase_from_client = normcase
if os == 'WINDOWS':
# Client in Windows and server in Unix, we need to normalize the case.
if not IS_WINDOWS:
_normcase_from_client = _normcase_windows
else:
# Client in Unix and server in Windows, we can't normalize the case.
if IS_WINDOWS:
_normcase_from_client = _normcase_linux
if prev != os:
_ide_os = os
# We need to (re)setup how the client <-> server translation works to provide proper separators.
setup_client_server_paths(_last_client_server_paths_set) | We need to set the IDE os because the host where the code is running may be actually different from the client (and the point is that we want the proper paths to translate from the client to the server). :param os: 'UNIX' or 'WINDOWS' |
177,071 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \
DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8
from _pydev_bundle.pydev_log import error_once
import json
import os.path
import sys
import itertools
import ntpath
from functools import partial
os_path_exists = os.path.exists
join = os.path.join
def _get_relative_filename_abs_path(filename, func, os_path_exists=os_path_exists):
# If we have a relative path and the file does not exist when made absolute, try to
# resolve it based on the sys.path entries.
for p in sys.path:
r = func(os.path.join(p, filename))
if os_path_exists(r):
return r
# We couldn't find the real file for the relative path. Resolve it as if it was in
# a library (so that it's considered a library file and not a project file).
r = func(os.path.join(_library_dir, filename))
return r
_ZIP_SEARCH_CACHE = {}
_NOT_FOUND_SENTINEL = object()
def exists(filename):
if os_path_exists(filename):
return True
if not os.path.isabs(filename):
filename = _get_relative_filename_abs_path(filename, os.path.abspath)
if os_path_exists(filename):
return True
ind = filename.find('.zip')
if ind == -1:
ind = filename.find('.egg')
if ind != -1:
ind += 4
zip_path = filename[:ind]
inner_path = filename[ind:]
if inner_path.startswith("!"):
# Note (fabioz): although I can replicate this by creating a file ending as
# .zip! or .egg!, I don't really know what's the real-world case for this
# (still kept as it was added by @jetbrains, but it should probably be reviewed
# later on).
# Note 2: it goes hand-in-hand with '_apply_func_and_normalize_case'.
inner_path = inner_path[1:]
zip_path = zip_path + '!'
zip_file_obj = _ZIP_SEARCH_CACHE.get(zip_path, _NOT_FOUND_SENTINEL)
if zip_file_obj is None:
return False
elif zip_file_obj is _NOT_FOUND_SENTINEL:
try:
import zipfile
zip_file_obj = zipfile.ZipFile(zip_path, 'r')
_ZIP_SEARCH_CACHE[zip_path] = zip_file_obj
except:
_ZIP_SEARCH_CACHE[zip_path] = _NOT_FOUND_SENTINEL
return False
try:
if inner_path.startswith('/') or inner_path.startswith('\\'):
inner_path = inner_path[1:]
_info = zip_file_obj.getinfo(inner_path.replace('\\', '/'))
return join(zip_path, inner_path)
except KeyError:
return False
else:
pydev_log.debug('os.path.exists(%r) returned False.', filename)
return False | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.