desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'inferred lookup return an iterator on inferred values of the statements returned by the lookup method'
def ilookup(self, name):
(frame, stmts) = self.lookup(name) context = contextmod.InferenceContext() return bases._infer_stmts(stmts, context, frame)
'filter statements to remove ignorable statements. If self is not a frame itself and the name is found in the inner frame locals, statements will be filtered to remove ignorable statements according to self\'s location'
def _filter_stmts(self, stmts, frame, offset):
if (offset == (-1)): myframe = self.frame().parent.frame() else: myframe = self.frame() if ((self.statement() is myframe) and myframe.parent): myframe = myframe.parent.frame() mystmt = self.statement() if ((myframe is frame) and (mystmt.fromlineno is not None)): ...
'return arguments formatted as string'
def format_args(self):
result = [] if self.args: result.append(_format_args(self.args, self.defaults, getattr(self, 'annotations', None))) if self.vararg: result.append(('*%s' % self.vararg)) if self.kwonlyargs: if (not self.vararg): result.append('*') result.append(_format_args(sel...
'return the default value for an argument :raise `NoDefault`: if there is no default value defined'
def default_value(self, argname):
i = _find_arg(argname, self.args)[0] if (i is not None): idx = (i - (len(self.args) - len(self.defaults))) if (idx >= 0): return self.defaults[idx] i = _find_arg(argname, self.kwonlyargs)[0] if ((i is not None) and (self.kw_defaults[i] is not None)): return self.kw_de...
'return True if the name is defined in arguments'
def is_argument(self, name):
if (name == self.vararg): return True if (name == self.kwarg): return True return ((self.find_argname(name, True)[1] is not None) or (self.kwonlyargs and (_find_arg(name, self.kwonlyargs, True)[1] is not None)))
'return index and Name node with given name'
def find_argname(self, argname, rec=False):
if self.args: return _find_arg(argname, self.args, rec) return (None, None)
'override get_children to skip over None elements in kw_defaults'
def get_children(self):
for child in super(Arguments, self).get_children(): if (child is not None): (yield child)
'Return a list of TypeErrors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage`, which holds the original exception.'
def type_errors(self, context=None):
try: results = self._infer_augassign(context=context) return [result for result in results if isinstance(result, util.BadBinaryOperationMessage)] except exceptions.InferenceError: return []
'Return a list of TypeErrors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage`, which holds the original exception.'
def type_errors(self, context=None):
try: results = self._infer_binop(context=context) return [result for result in results if isinstance(result, util.BadBinaryOperationMessage)] except exceptions.InferenceError: return []
'override get_children for tuple fields'
def get_children(self):
(yield self.left) for (_, comparator) in self.ops: (yield comparator)
'override last_child'
def last_child(self):
return self.ops[(-1)][1]
'method used in filter_stmts'
def _get_filtered_stmts(self, lookup_node, node, stmts, mystmt):
if (self is mystmt): if isinstance(lookup_node, (Const, Name)): return ([lookup_node], True) elif (self.statement() is mystmt): return ([node], True) return (stmts, False)
'get children of a Dict node'
def get_children(self):
for (key, value) in self.items: (yield key) (yield value)
'override last_child'
def last_child(self):
if self.items: return self.items[(-1)][1] return None
'handle block line numbers range for if statements'
def block_range(self, lineno):
if (lineno == self.body[0].fromlineno): return (lineno, lineno) if (lineno <= self.body[(-1)].tolineno): return (lineno, self.body[(-1)].tolineno) return self._elsed_block_range(lineno, self.orelse, (self.body[0].fromlineno - 1))
'Wrap the empty attributes of the Slice in a Const node.'
def _wrap_attribute(self, attr):
if (not attr): const = const_factory(attr) const.parent = self return const return attr
'handle block line numbers range for try/except statements'
def block_range(self, lineno):
last = None for exhandler in self.handlers: if (exhandler.type and (lineno == exhandler.type.fromlineno)): return (lineno, lineno) if (exhandler.body[0].fromlineno <= lineno <= exhandler.body[(-1)].tolineno): return (lineno, exhandler.body[(-1)].tolineno) if (last...
'handle block line numbers range for try/finally statements'
def block_range(self, lineno):
child = self.body[0] if (isinstance(child, TryExcept) and (child.fromlineno == self.fromlineno) and (lineno > self.fromlineno) and (lineno <= child.tolineno)): return child.block_range(lineno) return self._elsed_block_range(lineno, self.finalbody)
'Return a list of TypeErrors which can occur during inference. Each TypeError is represented by a :class:`BadUnaryOperationMessage`, which holds the original exception.'
def type_errors(self, context=None):
try: results = self._infer_unaryop(context=context) return [result for result in results if isinstance(result, util.BadUnaryOperationMessage)] except exceptions.InferenceError: return []
'handle block line numbers range for and while statements'
def block_range(self, lineno):
return self._elsed_block_range(lineno, self.orelse)
'Inference on an Unknown node immediately terminates.'
def infer(self, context=None, **kwargs):
(yield util.Uninferable)
'build astroid from a living module (i.e. using inspect) this is used when there is no python source code available (either because it\'s a built-in module or because the .py is not available)'
def inspect_build(self, module, modname=None, path=None):
self._module = module if (modname is None): modname = module.__name__ try: node = build_module(modname, module.__doc__) except AttributeError: node = build_module(modname) node.file = node.path = (os.path.abspath(path) if path else path) node.name = modname MANAGER.ca...
'recursive method which create a partial ast from real objects (only function, class, and method are handled)'
def object_build(self, node, obj):
if (obj in self._done): return self._done[obj] self._done[obj] = node for name in dir(obj): try: member = getattr(obj, name) except AttributeError: attach_dummy_node(node, name) continue if inspect.ismethod(member): member = six...
'verify this is not an imported class or handle it'
def imported_member(self, node, member, name):
try: modname = getattr(member, '__module__', None) except: _LOG.exception('unexpected error while building astroid from living object') modname = None if (modname is None): if ((name in ('__new__', '__subclasshook__')) or ((name in _BUILTINS) and _JYTHON)...
'Call matching transforms for the given node if any and return the transformed node.'
def _transform(self, node):
cls = node.__class__ if (cls not in self.transforms): return node transforms = self.transforms[cls] orig_node = node for (transform_func, predicate) in transforms: if ((predicate is None) or predicate(node)): ret = transform_func(node) if (ret is not None): ...
'Register `transform(node)` function to be applied on the given astroid\'s `node_class` if `predicate` is None or returns true when called with the node as argument. The transform function may return a value which is then used to substitute the original node in the tree.'
def register_transform(self, node_class, transform, predicate=None):
self.transforms[node_class].append((transform, predicate))
'Unregister the given transform.'
def unregister_transform(self, node_class, transform, predicate=None):
self.transforms[node_class].remove((transform, predicate))
'Walk the given astroid *tree* and transform each encountered node Only the nodes which have transforms registered will actually be replaced or changed.'
def visit(self, module):
module.body = [self._visit(child) for child in module.body] return self._transform(module)
'Determine if this path should be linted.'
def allow(self, path):
return path.endswith('.py')
'Lint the file. Return an array of error dicts if appropriate.'
def run(self, path, **meta):
with open(os.devnull, 'w') as devnull: sys.stdout = devnull if SortImports(path, check=True).incorrectly_sorted: return [{'lnum': 0, 'col': 0, 'text': 'Incorrectly sorted imports.', 'type': 'ISORT'}] else: return []
'Get options from config files.'
def finalize_options(self):
self.arguments = {} computed_settings = from_path(os.getcwd()) for (key, value) in itemsview(computed_settings): self.arguments[key] = value
'Find distribution packages.'
def distribution_files(self):
if self.distribution.packages: package_dirs = (self.distribution.package_dir or {}) for package in self.distribution.packages: pkg_dir = package if (package in package_dirs): pkg_dir = package_dirs[package] elif (u'' in package_dirs): ...
'Strips # comments that exist at the top of the given lines'
@staticmethod def _strip_top_comments(lines):
lines = copy.copy(lines) while (lines and lines[0].startswith(u'#')): lines = lines[1:] return u'\n'.join(lines)
'Tries to determine if a module is a python std import, third party import, or project code: if it can\'t determine - it assumes it is project code'
def place_module(self, module_name):
for forced_separate in self.config[u'forced_separate']: path_glob = forced_separate if (not forced_separate.endswith(u'*')): path_glob = (u'%s*' % forced_separate) if (fnmatch(module_name, path_glob) or fnmatch(module_name, (u'.' + path_glob))): return forced_separate...
'Returns the current line from the file while incrementing the index.'
def _get_line(self):
line = self.in_lines[self.index] self.index += 1 return line
'If the current line is an import line it will return its type (from or straight)'
@staticmethod def _import_type(line):
if (u'isort:skip' in line): return elif line.startswith(u'import '): return u'straight' elif line.startswith(u'from '): return u'from'
'returns True if we are at the end of the file.'
def _at_end(self):
return (self.index == self.number_of_lines)
'Returns a string with comments added'
def _add_comments(self, comments, original_string=u''):
return ((comments and u'{0} # {1}'.format(self._strip_comments(original_string)[0], u'; '.join(comments))) or original_string)
'Returns an import wrapped to the specified line-length, if possible.'
def _wrap(self, line):
wrap_mode = self.config[u'multi_line_output'] if ((len(line) > self.config[u'line_length']) and (wrap_mode != settings.WrapModes.NOQA)): for splitter in (u'import', u'.', u'as'): exp = ((u'\\b' + re.escape(splitter)) + u'\\b') if (re.search(exp, line) and (not line.strip().starts...
'Adds the imports back to the file. (at the index of the first import) sorted alphabetically and split between groups'
def _add_formatted_imports(self):
sort_ignore_case = self.config[u'force_alphabetical_sort_within_sections'] sections = itertools.chain(self.sections, self.config[u'forced_separate']) if self.config[u'no_sections']: self.imports[u'no_sections'] = {u'straight': [], u'from': {}} for section in sections: self.import...
'Removes comments from import line.'
@staticmethod def _strip_comments(line, comments=None):
if (comments is None): comments = [] new_comments = False comment_start = line.find(u'#') if (comment_start != (-1)): comments.append(line[(comment_start + 1):].strip()) new_comments = True line = line[:comment_start] return (line, comments, new_comments)
'Parses a python file taking out and categorizing imports.'
def _parse(self):
self._in_quote = False self._in_top_comment = False while (not self._at_end()): line = self._get_line() statement_index = self.index skip_line = self._skip_line(line) if ((line in self._section_comments) and (not skip_line)): if (self.import_index == (-1)): ...
'@ivar s_size search string size @ivar s search string @ivar substring index to longest matching substring @ivar result of the lookup @ivar method method to use if substring matches'
def __init__(self, s, substring_i, result, method=None):
self.s_size = len(s) self.s = s self.substring_i = substring_i self.result = result self.method = method
'Set the self.current string.'
def set_current(self, value):
self.current = value self.cursor = 0 self.limit = len(self.current) self.limit_backward = 0 self.bra = self.cursor self.ket = self.limit
'Get the self.current string.'
def get_current(self):
return self.current
'find_among_b is for backwards processing. Same comments apply'
def find_among_b(self, v, v_size):
i = 0 j = v_size c = self.cursor lb = self.limit_backward common_i = 0 common_j = 0 first_key_inspected = False while True: k = (i + ((j - i) >> 1)) diff = 0 common = min(common_i, common_j) w = v[k] for i2 in range(((w.s_size - 1) - common), (-1),...
'to replace chars between c_bra and c_ket in self.current by the chars in s. @type c_bra int @type c_ket int @type s: string'
def replace_s(self, c_bra, c_ket, s):
adjustment = (len(s) - (c_ket - c_bra)) self.current = ((self.current[0:c_bra] + s) + self.current[c_ket:]) self.limit += adjustment if (self.cursor >= c_ket): self.cursor += adjustment elif (self.cursor > c_bra): self.cursor = c_bra return adjustment
'@type s string'
def slice_from(self, s):
result = False if self.slice_check(): self.replace_s(self.bra, self.ket, s) result = True return result
'@type c_bra int @type c_ket int @type s: string'
def insert(self, c_bra, c_ket, s):
adjustment = self.replace_s(c_bra, c_ket, s) if (c_bra <= self.bra): self.bra += adjustment if (c_bra <= self.ket): self.ket += adjustment
'Copy the slice into the supplied StringBuffer @type s: string'
def slice_to(self, s):
result = '' if self.slice_check(): result = self.current[self.bra:self.ket] return result
'@type s: string'
def assign_to(self, s):
return self.current[0:self.limit]
'Return whether importation needs an as clause.'
def _has_alias(self):
return (not (self.fullName.split('.')[(-1)] == self.name))
'Generate a source statement equivalent to the import.'
@property def source_statement(self):
if self._has_alias(): return ('import %s as %s' % (self.fullName, self.name)) else: return ('import %s' % self.fullName)
'Return import full name with alias.'
def __str__(self):
if self._has_alias(): return ((self.fullName + ' as ') + self.name) else: return self.fullName
'Return import full name with alias.'
def __str__(self):
if (self.real_name != self.name): return ((self.fullName + ' as ') + self.name) else: return self.fullName
'Return a generator for the assignments which have not been used.'
def unusedAssignments(self):
for (name, binding) in self.items(): if ((not binding.used) and (name not in self.globals) and (not self.usesLocals) and isinstance(binding, Assignment)): (yield (name, binding))
'Schedule a function handler to be called just before completion. This is used for handling function bodies, which must be deferred because code later in the file might modify the global scope. When `callable` is called, the scope at the time this is called will be restored, however it will contain any new bindings add...
def deferFunction(self, callable):
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
'Schedule an assignment handler to be called just after deferred function handlers.'
def deferAssignment(self, callable):
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
'Run the callables in C{deferred} using their associated scope stack.'
def runDeferred(self, deferred):
for (handler, scope, offset) in deferred: self.scopeStack = scope self.offset = offset handler()
'Look at scopes which have been fully examined and report names in them which were imported but unused.'
def checkDeadScopes(self):
for scope in self.deadScopes: if isinstance(scope, ClassScope): continue all_binding = scope.get('__all__') if (all_binding and (not isinstance(all_binding, ExportBinding))): all_binding = None if all_binding: all_names = set(all_binding.names) ...
'True, if lnode and rnode are located on different forks of IF/TRY'
def differentForks(self, lnode, rnode):
ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor) if parts: for items in parts: if (self.descendantOf(lnode, items, ancestor) ^ self.descendantOf(rnode, items, ancestor)): return True return False
'Called when a binding is altered. - `node` is the statement responsible for the change - `value` is the new value, a Binding instance'
def addBinding(self, node, value):
for scope in self.scopeStack[::(-1)]: if (value.name in scope): break existing = scope.get(value.name) if (existing and (not self.differentForks(node, existing.source))): parent_stmt = self.getParent(value.source) if (isinstance(existing, Importation) and isinstance(paren...
'Determine if the given node is a docstring, as long as it is at the correct place in the node tree.'
def isDocstring(self, node):
return (isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)))
'Keep track of globals declarations.'
def GLOBAL(self, node):
global_scope_index = (1 if self._in_doctest() else 0) global_scope = self.scopeStack[global_scope_index] if (self.scope is not global_scope): for node_name in node.names: node_value = Assignment(node_name, node) self.messages = [m for m in self.messages if ((not isinstance(m,...
'Handle occurrence of Name (which can be a load/store/delete access.)'
def NAME(self, node):
if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if ((node.id == 'locals') and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.hand...
'Check names used in a class definition, including its decorators, base classes, and the body of its definition. Additionally, add its name to the current scope.'
def CLASSDEF(self, node):
for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if (not PY2): for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) if (self.withDoctest and (not sel...
'Annotated assignments don\'t have annotations evaluated on function scope, hence the custom implementation. See: PEP 526.'
def ANNASSIGN(self, node):
if node.value: self.handleNode(node.target, node) if (not isinstance(self.scope, FunctionScope)): self.handleNode(node.annotation, node) if node.value: self.handleNode(node.value, node)
'Construct a L{Reporter}. @param warningStream: A file-like object where warnings will be written to. The stream\'s C{write} method must accept unicode. C{sys.stdout} is a good value. @param errorStream: A file-like object where error output will be written to. The stream\'s C{write} method must accept unicode. C{sys...
def __init__(self, warningStream, errorStream):
self._stdout = warningStream self._stderr = errorStream
'An unexpected error occurred trying to process C{filename}. @param filename: The path to a file that we could not process. @ptype filename: C{unicode} @param msg: A message explaining the problem. @ptype msg: C{unicode}'
def unexpectedError(self, filename, msg):
self._stderr.write(('%s: %s\n' % (filename, msg)))
'There was a syntax error in C{filename}. @param filename: The path to the file with the syntax error. @ptype filename: C{unicode} @param msg: An explanation of the syntax error. @ptype msg: C{unicode} @param lineno: The line number where the syntax error occurred. @ptype lineno: C{int} @param offset: The column on whi...
def syntaxError(self, filename, msg, lineno, offset, text):
line = text.splitlines()[(-1)] if (offset is not None): offset = (offset - (len(text) - len(line))) self._stderr.write(('%s:%d:%d: %s\n' % (filename, lineno, (offset + 1), msg))) else: self._stderr.write(('%s:%d: %s\n' % (filename, lineno, msg))) self._stderr.write(line) ...
'pyflakes found something wrong with the code. @param: A L{pyflakes.messages.Message}.'
def flake(self, message):
self._stdout.write(str(message)) self._stdout.write('\n')
'Construct a restructuring See class pydoc for more info about the arguments.'
def __init__(self, project, pattern, goal, args=None, imports=None, wildcards=None):
self.project = project self.pattern = pattern self.goal = goal self.args = args if (self.args is None): self.args = {} self.imports = imports if (self.imports is None): self.imports = [] self.wildcards = wildcards self.template = similarfinder.CodeTemplate(self.goal)
'Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring will be applied to all python files. `checks` argument has been deprecated. Use the `args` argument of the constructor. The usage of:: strchecks = {\'obj...
def get_changes(self, checks=None, imports=None, resources=None, task_handle=taskhandle.NullTaskHandle()):
if (checks is not None): warnings.warn('The use of checks parameter is deprecated; use the args parameter of the constructor instead.', DeprecationWarning, stacklevel=2) for (name, value) in checks.items(): self.args[name] = similarfinder._pydefi...
'Convert str to str dicts to str to PyObject dicts This function is here to ease writing a UI.'
def make_checks(self, string_checks):
checks = {} for (key, value) in string_checks.items(): is_pyname = ((not key.endswith('.object')) and (not key.endswith('.type'))) evaluated = self._evaluate(value, is_pyname=is_pyname) if (evaluated is not None): checks[key] = evaluated return checks
'Generate `Occurrence` instances'
def find_occurrences(self, resource=None, pymodule=None):
tools = _OccurrenceToolsCreator(self.project, resource=resource, pymodule=pymodule, docs=self.docs) for offset in self._textual_finder.find_offsets(tools.source_code): occurrence = Occurrence(tools, offset) for filter in self.filters: result = filter(occurrence) if (resul...
'Get the changes this refactoring makes :parameters: - `similar`: if `True`, similar expressions/statements are also replaced. - `global_`: if `True`, the extracted method/variable will be global.'
def get_changes(self, extracted_name, similar=False, global_=False):
info = _ExtractInfo(self.project, self.resource, self.start_offset, self.end_offset, extracted_name, variable=(self.kind == 'variable'), similar=similar, make_global=global_) new_contents = _ExtractPerformer(info).extract() changes = ChangeSet(('Extract %s <%s>' % (self.kind, extracted_name))) cha...
'Does the extracted piece contain return statement'
@property def returned(self):
if (self._returned is None): node = _parse_text(self.extracted) self._returned = usefunction._returns_last(node) return self._returned
'force a single import per statement'
def force_single_imports(self):
for import_stmt in self.imports[:]: import_info = import_stmt.import_info if (import_info.is_empty() or import_stmt.readonly): continue if (len(import_info.names_and_aliases) > 1): for name_and_alias in import_info.names_and_aliases: if hasattr(import_...
'Removes pyname when imported in ``from mod import x``'
def remove_pyname(self, pyname):
visitor = actions.RemovePyNameVisitor(self.project, self.pymodule, pyname, self._current_folder()) for import_stmt in self.imports: import_stmt.accept(visitor)
'Get the imported resource Returns `None` if module was not found.'
def get_imported_resource(self, context):
if (self.level == 0): return context.project.find_module(self.module_name, folder=context.folder) else: return context.project.find_relative_module(self.module_name, context.folder, self.level)
'Get the imported `PyModule` Raises `rope.base.exceptions.ModuleNotFoundError` if module could not be found.'
def get_imported_module(self, context):
if (self.level == 0): return context.project.get_module(self.module_name, context.folder) else: return context.project.get_relative_module(self.module_name, context.folder, self.level)
'The import statement for `resource`'
def get_import(self, resource):
module_name = libutils.modname(resource) return NormalImport(((module_name, None),))
'The from import statement for `name` in `resource`'
def get_from_import(self, resource, name):
module_name = libutils.modname(resource) names = [] if isinstance(name, list): names = [(imported, None) for imported in name] else: names = [(name, None)] return FromImport(module_name, 0, tuple(names))
'Create a multiproject proxy for the main refactoring `projects` are other project.'
def __init__(self, refactoring, projects, addpath=True):
self.refactoring = refactoring self.projects = projects self.addpath = addpath
'Create the refactoring'
def __call__(self, project, *args, **kwds):
return _MultiRefactoring(self.refactoring, self.projects, self.addpath, project, *args, **kwds)
'Get a project to changes dict'
def get_all_changes(self, *args, **kwds):
result = [] for (project, refactoring) in zip(self.projects, self.refactorings): (args, kwds) = self._resources_for_args(project, args, kwds) result.append((project, refactoring.get_changes(*args, **kwds))) return result
'Construct a SimilarFinder'
def __init__(self, pymodule, wildcards=None):
self.source = pymodule.source_code try: self.raw_finder = RawSimilarFinder(pymodule.source_code, pymodule.get_ast(), self._does_match) except MismatchedTokenError: print ('in file %s' % pymodule.resource.path) raise self.pymodule = pymodule if (wildcards is None): ...
'Search for `code` in source and return a list of `Match`\es `code` can contain wildcards. ``${name}`` matches normal names and ``${?name} can match any expression. You can use `Match.get_ast()` for getting the node that has matched a given pattern.'
def get_matches(self, code, start=0, end=None, skip=None):
if (end is None): end = len(self.source) for match in self._get_matched_asts(code): (match_start, match_end) = match.get_region() if ((start <= match_start) and (match_end <= end)): if ((skip is not None) and ((skip[0] < match_end) and (skip[1] > match_start))): ...
'Searches the given pattern in the body AST. body is an AST node and pattern can be either an AST node or a list of ASTs nodes'
def __init__(self, body, pattern, does_match):
self.body = body self.pattern = pattern self.matches = None self.ropevar = _RopeVariable() self.matches_callback = does_match
'Return not `ast.expr_context` children of `node`'
def _get_children(self, node):
children = ast.get_children(node) return [child for child in children if (not isinstance(child, ast.expr_context))]
'Return the ast node that has matched rope variables'
def get_ast(self, name):
return self.mapping.get(name, None)
'Get the changes this refactoring makes `factory_name` indicates the name of the factory function to be added. If `global_factory` is `True` the factory will be global otherwise a static method is added to the class. `resources` can be a list of `rope.base.resource.File`\s that this refactoring should be applied on; i...
def get_changes(self, factory_name, global_factory=False, resources=None, task_handle=taskhandle.NullTaskHandle()):
if (resources is None): resources = self.project.get_python_files() changes = ChangeSet(('Introduce factory method <%s>' % factory_name)) job_set = task_handle.create_jobset('Collecting Changes', len(resources)) self._change_module(resources, changes, factory_name, global_factory, jo...
'Return the name of the class'
def get_name(self):
return self.old_name
'Get function arguments. Return a list of ``(name, default)`` tuples for all but star and double star arguments. For arguments that don\'t have a default, `None` will be used.'
def get_args(self):
return self._definfo().args_with_defaults
'Get changes caused by this refactoring `changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy` is `True` the changers are applyed to all matching methods in the class hierarchy. `resources` can be a list of `rope.base.resource.File`\s that should be searched for occurrences; if `None` all python files in the ...
def get_changes(self, changers, in_hierarchy=False, resources=None, task_handle=taskhandle.NullTaskHandle()):
function_changer = _FunctionChangers(self.pyname.get_object(), self._definfo(), changers) return self._change_calls(function_changer, in_hierarchy, resources, task_handle)
'Construct an `ArgumentReorderer` Note that the `new_order` is a list containing the new position of parameters; not the position each parameter is going to be moved to. (changed in ``0.5m4``) For example changing ``f(a, b, c)`` to ``f(c, a, b)`` requires passing ``[2, 0, 1]`` and *not* ``[1, 2, 0]``. The `autodef` (au...
def __init__(self, new_order, autodef=None):
self.new_order = new_order self.autodef = autodef
'Changes `children` and returns new start'
def _handle_parens(self, children, start, formats):
(opens, closes) = self._count_needed_parens(formats) old_end = self.source.offset new_end = None for i in range(closes): new_end = self.source.consume(')')[1] if (new_end is not None): if self.children: children.append(self.source[old_end:new_end]) new_start = start ...
'Checks whether consumed token is in comments'
def _good_token(self, token, offset, start=None):
if (start is None): start = self.offset try: comment_index = self.source.rindex('#', start, offset) except ValueError: return True try: new_line_index = self.source.rindex('\n', start, offset) except ValueError: return False return (comment_index < new_lin...
'If `offset` is None, the `resource` itself will be renamed'
def __init__(self, project, resource, offset=None):
self.project = project self.resource = resource if (offset is not None): self.old_name = worder.get_name_at(self.resource, offset) this_pymodule = self.project.get_pymodule(self.resource) (self.old_instance, self.old_pyname) = evaluate.eval_location2(this_pymodule, offset) if...
'Get the changes needed for this refactoring Parameters: - `in_hierarchy`: when renaming a method this keyword forces to rename all matching methods in the hierarchy - `docs`: when `True` rename refactoring will rename occurrences in comments and strings where the name is visible. Setting it will make renames faster, ...
def get_changes(self, new_name, in_file=None, in_hierarchy=False, unsure=None, docs=False, resources=None, task_handle=taskhandle.NullTaskHandle()):
if (unsure in (True, False)): warnings.warn('unsure parameter should be a function that returns True or False', DeprecationWarning, stacklevel=2) def unsure_func(value=unsure): return value unsure = unsure_func if (in_file is not None): w...