code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'Convert a structure into a Python native type.'
ctx = Context()
ContextFlags = self.ContextFlags
ctx['ContextFlags'] = ContextFlags
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in self._ctx_debug:
ctx[key] = getattr(... | def to_dict(self) | Convert a structure into a Python native type. | 2.519536 | 2.416372 | 1.042694 |
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
return "... | def _get_normal_name(orig_enc) | Imitates get_normal_name in tokenizer.c. | 2.18862 | 2.261822 | 0.967636 |
bom_found = False
encoding = None
default = 'utf-8'
def read_or_stop():
try:
return readline()
except StopIteration:
return bytes()
def find_cookie(line):
try:
line_string = line.decode('ascii')
except UnicodeDecodeError:
... | def detect_encoding(readline) | The detect_encoding() function is used to detect the encoding that should
be used to decode a Python source file. It requires one argment, readline,
in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used
(as a string) and a list of any lines ... | 2.677598 | 2.533142 | 1.057026 |
stdout = get_output(command)
return [line.strip().decode('utf-8') for line in stdout.splitlines()] | def get_lines(command) | Run a command and return lines of output
:param str command: the command to run
:returns: list of whitespace-stripped lines output by command | 3.571795 | 5.144831 | 0.694249 |
# Get list of files modified and staged
diff_cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"
files_modified = get_lines(diff_cmd)
errors = 0
for filename in files_modified:
if filename.endswith('.py'):
# Get the staged contents of the file
... | def git_hook(strict=False) | Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:return number of errors if in strict mode, 0 otherwise. | 3.858832 | 3.251586 | 1.186754 |
'''
Used so that it can work with the multiprocess plugin.
Monkeypatched because nose seems a bit unsupported at this time (ideally
the plugin would have this support by default).
'''
ret = original(self, result, batch_result)
parent_frame = sys._getframe().f_back
# addr is something as... | def new_consolidate(self, result, batch_result) | Used so that it can work with the multiprocess plugin.
Monkeypatched because nose seems a bit unsupported at this time (ideally
the plugin would have this support by default). | 8.39813 | 4.888126 | 1.718068 |
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(414)
return
... | def handle_one_request(self) | Handle a single HTTP request.
You normally don't need to override this method; see the class
__doc__ string for information on how to handle specific HTTP
commands such as GET and POST. | 1.607247 | 1.565253 | 1.026829 |
try:
short, long = self.responses[code]
except KeyError:
short, long = '???', '???'
if message is None:
message = short
explain = long
self.log_error("code %d, message %s", code, message)
# using _quote_html to prevent Cross S... | def send_error(self, code, message=None) | Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.
This sends an error response (so it must be called before any
output has been generated), logs the error, and finally ... | 3.026267 | 2.974406 | 1.017436 |
self.log_request(code)
if message is None:
if code in self.responses:
message = self.responses[code][0]
else:
message = ''
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s %d %s\r\n" %
... | def send_response(self, code, message=None) | Send the response header and log the response code.
Also send two standard headers with the server software
version and the current date. | 2.130124 | 1.943384 | 1.09609 |
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s: %s\r\n" % (keyword, value))
if keyword.lower() == 'connection':
if value.lower() == 'close':
self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close... | def send_header(self, keyword, value) | Send a MIME header. | 1.842965 | 1.934557 | 0.952655 |
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | def diff_texts(a, b, filename) | Return a unified diff of two strings. | 3.702302 | 3.241293 | 1.14223 |
if not isinstance(env_cmd, (list, tuple)):
env_cmd = [env_cmd]
if not os.path.exists(env_cmd[0]):
raise RuntimeError('Error: %s does not exist' % (env_cmd[0],))
# construct the command that will alter the environment
env_cmd = subprocess.list2cmdline(env_cmd)
# create a tag so ... | def get_environment_from_batch_command(env_cmd, initial=None) | Take a command (either a single command or list of arguments)
and return the environment created after running that command.
Note that if the command must be a batch file or .cmd file, or the
changes to the environment will not be captured.
If initial is supplied, it is used as the initial environment ... | 3.804396 | 3.796803 | 1.002 |
'Instance a new structure from a Python native type.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
s.ContextFlags = ContextFlags
for key in cls._others:
if key != 'VectorRegister':
setattr(s, key, ctx[key])
else:
... | def from_dict(cls, ctx) | Instance a new structure from a Python native type. | 2.611917 | 2.436762 | 1.07188 |
'Convert a structure into a Python dictionary.'
ctx = Context()
ContextFlags = self.ContextFlags
ctx['ContextFlags'] = ContextFlags
for key in self._others:
if key != 'VectorRegister':
ctx[key] = getattr(self, key)
else:
ctx... | def to_dict(self) | Convert a structure into a Python dictionary. | 2.682923 | 2.658976 | 1.009006 |
'''
We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work.
'''
try:
import java.lang.System
java.lang.System.exit(1)
except ImportError:
if len(args) == 1:
os.... | def do_exit(*args) | We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work. | 6.628554 | 2.326848 | 2.848727 |
frame = dbg.find_frame(thread_id, frame_id)
is_multiline = expression.count('@LINE@') > 1
expression = str(expression.replace('@LINE@', '\n'))
# Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329
# (Names not resolved in g... | def console_exec(thread_id, frame_id, expression, dbg) | returns 'False' in case expression is partially correct | 4.515952 | 4.494536 | 1.004765 |
# Override for avoid using sys.excepthook PY-12600
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
if filename and type is SyntaxError:
# Work hard to stuff the correct filename in the exception
... | def showsyntaxerror(self, filename=None) | Display the syntax error that just occurred. | 3.462815 | 3.428156 | 1.01011 |
# Override for avoid using sys.excepthook PY-12600
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
lines... | def showtraceback(self, *args, **kwargs) | Display the exception that just occurred. | 2.877247 | 2.782787 | 1.033945 |
for mbi in memory_map:
if condition(mbi):
address = mbi.BaseAddress
max_addr = address + mbi.RegionSize
while address < max_addr:
yield address
address = address + 1 | def CustomAddressIterator(memory_map, condition) | Generator function that iterates through a memory map, filtering memory
region blocks by any given condition.
@type memory_map: list( L{win32.MemoryBasicInformation} )
@param memory_map: List of memory region information objects.
Returned by L{Process.get_memory_map}.
@type condition: functi... | 3.45644 | 3.889311 | 0.888702 |
'x.next() -> the next value, or raise StopIteration'
if self.__g_object is None:
self.__g_object = self.__g_function( *self.__v_args, **self.__d_args )
try:
return self.__g_object.next()
except StopIteration:
self.__g_object = None
raise | def next(self) | x.next() -> the next value, or raise StopIteration | 4.036443 | 3.473567 | 1.162046 |
filepart = win32.PathRemoveExtension(pathname)
extpart = win32.PathFindExtension(pathname)
return (filepart, extpart) | def split_extension(pathname) | @type pathname: str
@param pathname: Absolute path.
@rtype: tuple( str, str )
@return:
Tuple containing the file and extension components of the filename. | 6.998876 | 8.680093 | 0.806313 |
filepart = win32.PathFindFileName(pathname)
pathpart = win32.PathRemoveFileSpec(pathname)
return (pathpart, filepart) | def split_filename(pathname) | @type pathname: str
@param pathname: Absolute path.
@rtype: tuple( str, str )
@return: Tuple containing the path to the file and the base filename. | 9.703165 | 10.836577 | 0.895409 |
components = list()
while path:
next = win32.PathFindNextComponent(path)
if next:
prev = path[ : -len(next) ]
components.append(prev)
path = next
return components | def split_path(path) | @see: L{join_path}
@type path: str
@param path: Absolute or relative path.
@rtype: list( str... )
@return: List of path components. | 6.335483 | 6.676151 | 0.948972 |
if components:
path = components[0]
for next in components[1:]:
path = win32.PathAppend(path, next)
else:
path = ""
return path | def join_path(*components) | @see: L{split_path}
@type components: tuple( str... )
@param components: Path components.
@rtype: str
@return: Absolute or relative path. | 4.352998 | 5.057655 | 0.860675 |
# XXX TODO
# There are probably some native paths that
# won't be converted by this naive approach.
if name.startswith(compat.b("\\")):
if name.startswith(compat.b("\\??\\")):
name = name[4:]
elif name.startswith(compat.b("\\SystemRoot\\")... | def native_to_win32_pathname(name) | @type name: str
@param name: Native (NT) absolute pathname.
@rtype: str
@return: Win32 absolute pathname. | 2.909487 | 2.976624 | 0.977445 |
try:
try:
pageSize = win32.GetSystemInfo().dwPageSize
except WindowsError:
pageSize = 0x1000
except NameError:
pageSize = 0x1000
cls.pageSize = pageSize # now this function won't be called again
return pageS... | def pageSize(cls) | Try to get the pageSize value on runtime. | 5.323501 | 4.792019 | 1.11091 |
if begin is None:
begin = 0
if end is None:
end = win32.LPVOID(-1).value # XXX HACK
if end < begin:
begin, end = end, begin
begin = cls.align_address_to_page_start(begin)
if end != cls.align_address_to_page_start(end):
end... | def align_address_range(cls, begin, end) | Align the given address range to the start and end of the page(s) it occupies.
@type begin: int
@param begin: Memory address of the beginning of the buffer.
Use C{None} for the first legal address in the address space.
@type end: int
@param end: Memory address of the end ... | 3.111008 | 3.031818 | 1.02612 |
if size < 0:
size = -size
address = address - size
begin, end = cls.align_address_range(address, address + size)
# XXX FIXME
# I think this rounding fails at least for address 0xFFFFFFFF size 1
return int(float(end - begin) / float(cls.pageSize... | def get_buffer_size_in_pages(cls, address, size) | Get the number of pages in use by the given buffer.
@type address: int
@param address: Aligned memory address.
@type size: int
@param size: Buffer size.
@rtype: int
@return: Buffer size in number of pages. | 8.787068 | 10.10724 | 0.869384 |
return (old_begin <= begin < old_end) or \
(old_begin < end <= old_end) or \
(begin <= old_begin < end) or \
(begin < old_end <= end) | def do_ranges_intersect(begin, end, old_begin, old_end) | Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
... | 2.383808 | 2.866249 | 0.831682 |
ctx['Dr7'] &= cls.clearMask[register]
ctx['Dr%d' % register] = 0 | def clear_bp(cls, ctx, register) | Clears a hardware breakpoint.
@see: find_slot, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register) for hardware breakpoint. | 19.687996 | 23.108784 | 0.85197 |
Dr7 = ctx['Dr7']
Dr7 |= cls.enableMask[register]
orMask, andMask = cls.triggerMask[register][trigger]
Dr7 &= andMask
Dr7 |= orMask
orMask, andMask = cls.watchMask[register][watch]
Dr7 &= andMask
Dr7 |= orMask
ctx['Dr7'] = Dr7
ctx['... | def set_bp(cls, ctx, register, address, trigger, watch) | Sets a hardware breakpoint.
@see: clear_bp, find_slot
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register).
@type address: int
@param address: Memory address.
@type trig... | 3.721597 | 4.817595 | 0.772501 |
Dr7 = ctx['Dr7']
slot = 0
for m in cls.enableMask:
if (Dr7 & m) == 0:
return slot
slot += 1
return None | def find_slot(cls, ctx) | Finds an empty slot to set a hardware breakpoint.
@see: clear_bp, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@rtype: int
@return: Slot (debug register) for hardware breakpoint. | 7.713511 | 10.819801 | 0.712907 |
self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off() | def run(self, graminit_h, graminit_c) | Load the grammar tables from the text files written by pgen. | 3.539627 | 3.319126 | 1.066433 |
try:
f = open(filename)
except IOError, err:
print "Can't open %s: %s" % (filename, err)
return False
self.symbol2number = {}
self.number2symbol = {}
lineno = 0
for line in f:
lineno += 1
mo = re.match(r... | def parse_graminit_h(self, filename) | Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back. | 2.200319 | 2.14424 | 1.026154 |
self.keywords = {} # map from keyword strings to arc labels
self.tokens = {} # map from numeric token values to arc labels
for ilabel, (type, value) in enumerate(self.labels):
if type == token.NAME and value is not None:
self.keywords[value] = ilabel
... | def finish_off(self) | Create additional useful structures. (Internal). | 5.929471 | 5.192935 | 1.141834 |
'''
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... | 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' | 5.867727 | 3.840418 | 1.527888 |
for path in paths:
if os.path.isdir(path):
if should_skip(path, config, os.getcwd()):
skipped.append(path)
continue
for dirpath, dirnames, filenames in os.walk(path, topdown=True):
for dirname in list(dirnames):
... | def iter_source_code(paths, config, skipped) | Iterate over all Python source files defined in paths. | 1.817809 | 1.81742 | 1.000214 |
'''
This is necessary so that we get the imports from the same directory where the file
we are completing is located.
'''
global currDirModule
if currDirModule is not None:
if len(sys.path) > 0 and sys.path[0] == currDirModule:
del sys.path[0]
currDirModule = directory
... | def complete_from_dir(directory) | This is necessary so that we get the imports from the same directory where the file
we are completing is located. | 4.626849 | 2.618431 | 1.767031 |
'''Changes the pythonpath (clears all the previous pythonpath)
@param pythonpath: string with paths separated by |
'''
split = pythonpath.split('|')
sys.path = []
for path in split:
path = path.strip()
if len(path) > 0:
sys.path.append(path) | def change_python_path(pythonpath) | Changes the pythonpath (clears all the previous pythonpath)
@param pythonpath: string with paths separated by | | 4.174964 | 2.434766 | 1.71473 |
'''
Format the completions suggestions in the following format:
@@COMPLETIONS(modFile(token,description),(token,description),(token,description))END@@
'''
compMsg = []
compMsg.append('%s' % defFile)
for tup in completionsList:
compMsg.append(',')
... | def format_completion_message(self, defFile, completionsList) | Format the completions suggestions in the following format:
@@COMPLETIONS(modFile(token,description),(token,description),(token,description))END@@ | 3.425508 | 2.211473 | 1.548971 |
'''
When we receive this, we have 'token):data'
'''
token = ''
for c in data:
if c != ')':
token = token + c
else:
break;
return token, data.lstrip(token + '):') | def get_token_and_data(self, data) | When we receive this, we have 'token):data' | 8.76199 | 4.040827 | 2.168365 |
# Support people who used socket.settimeout() to escape
# handle_request before self.timeout was available.
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(timeout, self.ti... | def handle_request(self) | Handle one request, possibly blocking.
Respects self.timeout. | 4.489953 | 4.043073 | 1.11053 |
print '-'*40
print 'Exception happened during processing of request from',
print client_address
import traceback
traceback.print_exc() # XXX But this goes to stderr!
print '-'*40 | def handle_error(self, request, client_address) | Handle an error gracefully. May be overridden.
The default is to print a traceback and continue. | 7.511523 | 7.162993 | 1.048657 |
if self.active_children is None: return
while len(self.active_children) >= self.max_children:
# XXX: This will wait for any child process, not just ones
# spawned by this library. This could confuse other
# libraries that expect to be able to wait for their o... | def collect_children(self) | Internal routine to wait for children that have exited. | 4.615796 | 4.336387 | 1.064433 |
self.collect_children()
pid = os.fork() # @UndefinedVariable
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request) #close handle in... | def process_request(self, request, client_address) | Fork a new subprocess to process the request. | 3.698458 | 3.393108 | 1.089991 |
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except:
self.handle_error(request, client_address)
self.shutdown_request(request) | def process_request_thread(self, request, client_address) | Same as in BaseServer but as a thread.
In addition, exception handling is done here. | 2.21005 | 2.127422 | 1.038839 |
#already imported Qt somewhere. Use that
loaded = loaded_api()
if loaded is not None:
return [loaded]
mpl = sys.modules.get('matplotlib', None)
if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
#1.0.1 only supports PyQt4 v1
return [QT_API_PYQT_DEFAULT... | def get_options() | Return a list of acceptable QT APIs, in decreasing order of
preference | 9.672668 | 8.516497 | 1.135757 |
r
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" | 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 o... | 6.889033 | 6.532241 | 1.05462 |
r
indent = INDENT_REGEX.match(physical_line).group(1)
if '\t' in indent:
return indent.index('\t'), "W191 indentation contains tabs" | def tabs_obsolete(physical_line) | r"""For new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn | 11.050636 | 6.651592 | 1.661352 |
r
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 str... | 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 | 3.878755 | 3.710911 | 1.04523 |
r
if line_number == total_lines:
stripped_last_line = physical_line.rstrip()
if not stripped_last_line:
return 0, "W391 blank line at end of file"
if stripped_last_line == physical_line:
return len(physical_line), "W292 no newline at end of file" | 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). | 3.934124 | 3.454542 | 1.138826 |
r
line = physical_line.rstrip()
length = len(line)
if length > max_line_length and not noqa:
# 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) == ... | def maximum_line_length(physical_line, max_line_length, multiline, 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 l... | 4.127929 | 3.831217 | 1.077446 |
r
if line_number < 3 and not previous_logical:
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 > 2 or (indent_level and blank_lines == 2):... | 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.... | 3.581564 | 3.627487 | 0.98734 |
r
line = logical_line
for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line):
text = match.group()
char = text.strip()
found = match.start()
if text == char + ' ':
# assert char in '([{'
yield found + 1, "E201 whitespace after '%s'" % char
eli... | 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(... | 5.321491 | 5.157464 | 1.031804 |
r
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:
... | 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 | 2.816622 | 2.572577 | 1.094864 |
r
line = logical_line
indicator = ' import('
if line.startswith('from '):
found = line.find(indicator)
if -1 < found:
pos = found + len(indicator) - 1
yield pos, "E275 missing whitespace after keyword" | def missing_whitespace_after_import_keyword(logical_line) | r"""Multiple imports in form from x import (a, b, c) should have space
between import statement and parenthesised name list.
Okay: from foo import (bar, baz)
E275: from foo import(bar, baz)
E275: from importable.module import(bar, baz) | 9.849836 | 7.412734 | 1.328772 |
r
line = logical_line
for index in range(len(line) - 1):
char = line[index]
if char in ',;:' and line[index + 1] not in WHITESPACE:
before = line[:index]
if char == ':' and before.count('[') > before.count(']') and \
before.rfind('{') < before.rfin... | def missing_whitespace(logical_line) | r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
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'}] | 5.089118 | 4.193691 | 1.213518 |
r
c = 0 if logical_line else 3
tmpl = "E11%d %s" if logical_line else "E11%d %s (comment)"
if indent_level % 4:
yield 0, tmpl % (1 + c, "indentation is not a multiple of four")
indent_expect = previous_logical.endswith(':')
if indent_expect and indent_level <= previous_indent_level:
... | def indentation(logical_line, previous_logical, indent_char,
indent_level, previous_indent_level) | r"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:\n pass
E112: for item in items:\npass
E115: for item ... | 4.233495 | 5.089162 | 0.831865 |
r
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 '... | 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'] = li... | 4.395325 | 4.536428 | 0.968895 |
r
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:
... | 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 | 2.716539 | 2.602749 | 1.043719 |
r
parens = 0
need_space = False
prev_type = tokenize.OP
prev_text = prev_end = None
for token_type, text, start, end, line in tokens:
if token_type in SKIP_COMMENTS:
continue
if text in ('(', 'lambda'):
parens += 1
elif text == ')':
par... | 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... | 4.439976 | 4.494655 | 0.987835 |
r
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] | 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) | 5.042008 | 5.118779 | 0.985002 |
r
parens = 0
no_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"
for token_type, text, start, end, line in tokens:
if token_type == tokenize.NL:
... | 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.
Okay: def complex(real, imag=0.0):
Okay: return magic(r=real, i=imag)
Okay: boolean(a == b)
Okay: boolean(a != b)
Okay... | 3.399623 | 3.56606 | 0.953327 |
r
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,... | def whitespace_before_comment(logical_line, tokens) | r"""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 a single ... | 4.533707 | 4.340089 | 1.044612 |
r
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" | 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 | 7.503834 | 7.958257 | 0.942899 |
r
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_try_keywords = ('try', 'except', 'else', 'finally')
if indent_level: # Allow imp... | 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 ... | 3.737855 | 3.814434 | 0.979924 |
r
line = logical_line
last_char = len(line) - 1
found = line.find(':')
prev_found = 0
counts = dict((char, 0) for char in '{}[]()')
while -1 < found < last_char:
update_counts(line[prev_found:found], counts)
if ((counts['{'] <= counts['}'] and # {'a': 1} (dict)
... | 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
... | 3.958085 | 3.724052 | 1.062844 |
r
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... | 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 us... | 3.446091 | 3.292944 | 1.046508 |
r
def is_binary_operator(token_type, text):
# The % character is strictly speaking a binary operator, but the
# common usage seems to be to put it next to the format parameters,
# after a line break.
return ((token_type == tokenize.OP or text in ['and', 'or']) and
... | def break_around_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)
Okay: (width == 0 +\n height == 0)
Okay: foo(\n -x)
Okay: foo(x\n [])
... | 4.677857 | 4.343306 | 1.077027 |
r
match = not noqa and COMPARE_SINGLETON_REGEX.search(logical_line)
if match:
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'
... | 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:
A... | 5.281778 | 5.142367 | 1.02711 |
r
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'" | 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.... | 5.384499 | 5.043462 | 1.06762 |
r
match = COMPARE_TYPE_REGEX.search(logical_line)
if match and not noqa:
inst = match.group(1)
if inst and isidentifier(inst) and inst not in SINGLETONS:
return # Allow comparison for types which are not obvious
yield match.start(), "E721 do not compare types, use 'isins... | 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
... | 9.223812 | 10.105536 | 0.912748 |
r
if noqa:
return
regex = re.compile(r"except\s*:")
match = regex.match(logical_line)
if match:
yield match.start(), "E722 do not use bare except'" | def bare_except(logical_line, noqa) | r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except: | 6.200561 | 7.618948 | 0.813834 |
r
idents_to_avoid = ('l', 'O', 'I')
prev_type, prev_text, prev_start, prev_end, __ = tokens[0]
for token_type, text, start, end, line in tokens[1:]:
ident = pos = None
# identifiers on the lhs of an assignment operator
if token_type == tokenize.OP and '=' in text:
if ... | 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 ... | 3.341382 | 3.049981 | 1.095542 |
r
match = RAISE_COMMA_REGEX.match(logical_line)
if match and not RERAISE_COMMA_REGEX.match(logical_line):
yield match.end() - 1, "W602 deprecated form of raising exception" | def python_3000_raise_comma(logical_line) | r"""When raising an exception, use "raise ValueError('message')".
The older form is removed in Python 3.
Okay: raise DummyError("Message")
W602: raise DummyError, "Message" | 7.607271 | 6.382104 | 1.191969 |
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 | 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 | 2.9502 | 2.701258 | 1.092158 |
# 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:] | 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'" | 4.616564 | 4.778709 | 0.966069 |
# 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] == '@... | def parse_udiff(diff, patterns=None, parent='.') | Return a dictionary of matching lines. | 4.010731 | 3.735915 | 1.073561 |
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 | def normalize_paths(value, parent=os.curdir) | Parse a comma-separated list of paths.
Return a list of absolute paths. | 2.203196 | 2.183758 | 1.008901 |
if not patterns:
return default
return any(fnmatch(filename, pattern) for pattern in patterns) | def filename_match(filename, patterns, default=True) | Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True. | 2.976383 | 3.565444 | 0.834786 |
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 ('ph... | def register_check(check, codes=None) | Register a new check object. | 3.417615 | 3.485263 | 0.98059 |
mod = inspect.getmodule(register_check)
for (name, function) in inspect.getmembers(mod, inspect.isfunction):
register_check(function) | def init_checks_registry() | Register all globally visible functions.
The first argument name is either 'physical_line' or 'logical_line'. | 4.203311 | 4.267742 | 0.984903 |
parser = OptionParser(prog=prog, version=version,
usage="%prog [options] input ...")
parser.config_options = [
'exclude', 'filename', 'select', 'ignore', 'max-line-length',
'hang-closing', 'count', 'format', 'quiet', 'show-pep8',
'show-source', 'statistics'... | def get_parser(prog='pycodestyle', version=__version__) | Create the parser for the program. | 2.881841 | 2.879701 | 1.000743 |
config = 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.... | 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 ... | 2.960046 | 2.875094 | 1.029548 |
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 "
... | def process_options(arglist=None, parse_argv=False, config_file=None,
parser=None) | Process options passed either via arglist or via 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. | 4.985874 | 4.93073 | 1.011184 |
r
if options:
return [o.strip() for o in options.split(split_token) if o.strip()]
else:
return options | def _parse_multi_options(options, split_token=',') | r"""Split and strip and discard empties.
Turns the following:
A,
B,
into ["A", "B"] | 3.969814 | 4.716464 | 0.841693 |
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 o... | def _main() | Parse options and run checks on Python source. | 3.529545 | 3.369069 | 1.047632 |
(exc_type, exc) = sys.exc_info()[:2]
if len(exc.args) > 1:
offset = exc.args[1]
if len(offset) > 2:
offset = offset[1:3]
else:
offset = (1, 0)
self.report_error(offset[0], offset[1] or 0,
'E901 %s: %s'... | def report_invalid_syntax(self) | Check if the syntax is valid. | 3.61379 | 3.557021 | 1.01596 |
if self.line_number >= self.total_lines:
return ''
line = self.lines[self.line_number]
self.line_number += 1
if self.indent_char is None and line[:1] in WHITESPACE:
self.indent_char = line[0]
return line | def readline(self) | Get the next line from the input buffer. | 2.903085 | 2.893096 | 1.003452 |
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments) | def run_check(self, check, argument_names) | Run a check plugin. | 3.059523 | 3.028769 | 1.010154 |
if 'checker_state' in argument_names:
self.checker_state = self._checker_states.setdefault(name, {}) | def init_checker_state(self, name, argument_names) | Prepare custom state for the specific checker plugin. | 4.745984 | 4.367291 | 1.086711 |
self.physical_line = line
for name, check, argument_names in self._physical_checks:
self.init_checker_state(name, argument_names)
result = self.run_check(check, argument_names)
if result is not None:
(offset, text) = result
sel... | def check_physical(self, line) | Run all physical checks on a raw input line. | 5.476067 | 5.164926 | 1.060241 |
logical = []
comments = []
length = 0
prev_row = prev_col = mapping = None
for token_type, text, start, end, line in self.tokens:
if token_type in SKIP_TOKENS:
continue
if not mapping:
mapping = [(0, start)]
... | def build_tokens_line(self) | Build a logical line from tokens. | 3.520154 | 3.341537 | 1.053453 |
self.report.increment_logical_line()
mapping = self.build_tokens_line()
if not mapping:
return
(start_row, start_col) = mapping[0][1]
start_line = self.lines[start_row - 1]
self.indent_level = expand_indent(start_line[:start_col])
if self.bl... | def check_logical(self) | Build a line from tokens and run all logical checks on it. | 4.035465 | 3.739777 | 1.079066 |
try:
tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
except (ValueError, SyntaxError, TypeError):
return self.report_invalid_syntax()
for name, cls, __ in self._ast_checks:
checker = cls(tree, self.filename)
for lineno, offs... | def check_ast(self) | Build the file's AST and run all AST checks. | 5.034952 | 4.533129 | 1.110701 |
if self._io_error:
self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
tokengen = tokenize.generate_tokens(self.readline)
try:
for token in tokengen:
if token[2][0] > self.total_lines:
return
self.noq... | def generate_tokens(self) | Tokenize the file, run physical line checks and yield tokens. | 7.174519 | 6.197115 | 1.157719 |
# Called after every token, but act only on end of line.
if _is_eol_token(token):
# Obviously, a newline token ends a single physical line.
self.check_physical(token[4])
elif token[0] == tokenize.STRING and '\n' in token[1]:
# Less obviously, a string... | def maybe_check_physical(self, token) | If appropriate (based on token), check current physical line(s). | 7.140305 | 6.902499 | 1.034452 |
self.report.init_file(self.filename, self.lines, expected, line_offset)
self.total_lines = len(self.lines)
if self._ast_checks:
self.check_ast()
self.line_number = 0
self.indent_char = None
self.indent_level = self.previous_indent_level = 0
se... | def check_all(self, expected=None, line_offset=0) | Run all checks on the input file. | 3.194953 | 3.14818 | 1.014857 |
self.filename = filename
self.lines = lines
self.expected = expected or ()
self.line_offset = line_offset
self.file_errors = 0
self.counters['files'] += 1
self.counters['physical lines'] += len(lines) | def init_file(self, filename, lines, expected, line_offset) | Signal a new file. | 3.600369 | 3.244133 | 1.109809 |
code = text[:4]
if self._ignore_code(code):
return
if code in self.counters:
self.counters[code] += 1
else:
self.counters[code] = 1
self.messages[code] = text[5:]
# Don't care about expected errors or warnings
if co... | def error(self, line_number, offset, text, check) | Report an error, according to options. | 4.130691 | 3.942786 | 1.047658 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.