idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
16,900 | def get_last_line_number ( node ) : max_lineno = node . lineno while True : last_child = _get_last_child_with_lineno ( node ) if last_child is None : return max_lineno else : try : max_lineno = max ( max_lineno , last_child . lineno ) except AttributeError : pass node = last_child | Estimate last line number of the given AST node . |
16,901 | def _safe_eval ( node , default ) : if isinstance ( node , ast . BoolOp ) : results = [ _safe_eval ( value , default ) for value in node . values ] if isinstance ( node . op , ast . And ) : return all ( results ) else : return any ( results ) elif isinstance ( node , ast . UnaryOp ) and isinstance ( node . op , ast . Not ) : return not _safe_eval ( node . operand , not default ) else : try : return ast . literal_eval ( node ) except ValueError : return default | Safely evaluate the Boolean expression under the given AST node . |
16,902 | def get_modules ( paths , toplevel = True ) : modules = [ ] for path in paths : path = os . path . abspath ( path ) if toplevel and path . endswith ( '.pyc' ) : sys . exit ( '.pyc files are not supported: {0}' . format ( path ) ) if os . path . isfile ( path ) and ( path . endswith ( '.py' ) or toplevel ) : modules . append ( path ) elif os . path . isdir ( path ) : subpaths = [ os . path . join ( path , filename ) for filename in sorted ( os . listdir ( path ) ) ] modules . extend ( get_modules ( subpaths , toplevel = False ) ) elif toplevel : sys . exit ( 'Error: {0} could not be found.' . format ( path ) ) return modules | Take files from the command line even if they don t end with . py . |
16,903 | def get_unused_code ( self , min_confidence = 0 , sort_by_size = False ) : if not 0 <= min_confidence <= 100 : raise ValueError ( 'min_confidence must be between 0 and 100.' ) def by_name ( item ) : return ( item . filename . lower ( ) , item . first_lineno ) def by_size ( item ) : return ( item . size , ) + by_name ( item ) unused_code = ( self . unused_attrs + self . unused_classes + self . unused_funcs + self . unused_imports + self . unused_props + self . unused_vars + self . unreachable_code ) confidently_unused = [ obj for obj in unused_code if obj . confidence >= min_confidence ] return sorted ( confidently_unused , key = by_size if sort_by_size else by_name ) | Return ordered list of unused Item objects . |
16,904 | def report ( self , min_confidence = 0 , sort_by_size = False , make_whitelist = False ) : for item in self . get_unused_code ( min_confidence = min_confidence , sort_by_size = sort_by_size ) : print ( item . get_whitelist_string ( ) if make_whitelist else item . get_report ( add_size = sort_by_size ) ) self . found_dead_code_or_error = True return self . found_dead_code_or_error | Print ordered list of Item objects to stdout . |
16,905 | def _handle_ast_list ( self , ast_list ) : for index , node in enumerate ( ast_list ) : if isinstance ( node , ( ast . Break , ast . Continue , ast . Raise , ast . Return ) ) : try : first_unreachable_node = ast_list [ index + 1 ] except IndexError : continue class_name = node . __class__ . __name__ . lower ( ) self . _define ( self . unreachable_code , class_name , first_unreachable_node , last_node = ast_list [ - 1 ] , message = "unreachable code after '{class_name}'" . format ( ** locals ( ) ) , confidence = 100 ) return | Find unreachable nodes in the given sequence of ast nodes . |
16,906 | def find_occurrences ( project , resource , offset , unsure = False , resources = None , in_hierarchy = False , task_handle = taskhandle . NullTaskHandle ( ) ) : name = worder . get_name_at ( resource , offset ) this_pymodule = project . get_pymodule ( resource ) primary , pyname = rope . base . evaluate . eval_location2 ( this_pymodule , offset ) def is_match ( occurrence ) : return unsure finder = occurrences . create_finder ( project , name , pyname , unsure = is_match , in_hierarchy = in_hierarchy , instance = primary ) if resources is None : resources = project . get_python_files ( ) job_set = task_handle . create_jobset ( 'Finding Occurrences' , count = len ( resources ) ) return _find_locations ( finder , resources , job_set ) | Return a list of Location \ s |
16,907 | def find_implementations ( project , resource , offset , resources = None , task_handle = taskhandle . NullTaskHandle ( ) ) : name = worder . get_name_at ( resource , offset ) this_pymodule = project . get_pymodule ( resource ) pyname = rope . base . evaluate . eval_location ( this_pymodule , offset ) if pyname is not None : pyobject = pyname . get_object ( ) if not isinstance ( pyobject , rope . base . pyobjects . PyFunction ) or pyobject . get_kind ( ) != 'method' : raise exceptions . BadIdentifierError ( 'Not a method!' ) else : raise exceptions . BadIdentifierError ( 'Cannot resolve the identifier!' ) def is_defined ( occurrence ) : if not occurrence . is_defined ( ) : return False def not_self ( occurrence ) : if occurrence . get_pyname ( ) . get_object ( ) == pyname . get_object ( ) : return False filters = [ is_defined , not_self , occurrences . InHierarchyFilter ( pyname , True ) ] finder = occurrences . Finder ( project , name , filters = filters ) if resources is None : resources = project . get_python_files ( ) job_set = task_handle . create_jobset ( 'Finding Implementations' , count = len ( resources ) ) return _find_locations ( finder , resources , job_set ) | Find the places a given method is overridden . |
16,908 | def find_errors ( project , resource ) : pymodule = project . get_pymodule ( resource ) finder = _BadAccessFinder ( pymodule ) ast . walk ( pymodule . get_ast ( ) , finder ) return finder . errors | Find possible bad name and attribute accesses |
16,909 | def transform ( self , pyobject ) : if pyobject is None : return ( 'none' , ) object_type = type ( pyobject ) try : method = getattr ( self , object_type . __name__ + '_to_textual' ) return method ( pyobject ) except AttributeError : return ( 'unknown' , ) | Transform a PyObject to textual form |
16,910 | def transform ( self , textual ) : if textual is None : return None type = textual [ 0 ] try : method = getattr ( self , type + '_to_pyobject' ) return method ( textual ) except AttributeError : return None | Transform an object from textual form to PyObject |
16,911 | def get_patched_ast ( source , sorted_children = False ) : return patch_ast ( ast . parse ( source ) , source , sorted_children ) | Adds region and sorted_children fields to nodes |
16,912 | def patch_ast ( node , source , sorted_children = False ) : if hasattr ( node , 'region' ) : return node walker = _PatchingASTWalker ( source , children = sorted_children ) ast . call_for_nodes ( node , walker ) return node | Patches the given node |
16,913 | def write_ast ( patched_ast_node ) : result = [ ] for child in patched_ast_node . sorted_children : if isinstance ( child , ast . AST ) : result . append ( write_ast ( child ) ) else : result . append ( child ) return '' . join ( result ) | Extract source form a patched AST node with sorted_children field |
16,914 | 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 for i in range ( opens ) : new_start = self . source . rfind_token ( '(' , 0 , new_start ) if new_start != start : if self . children : children . appendleft ( self . source [ new_start : start ] ) start = new_start return start | Changes children and returns new start |
16,915 | 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_line_index | Checks whether consumed token is in comments |
16,916 | def get_block_start ( lines , lineno , maximum_indents = 80 ) : pattern = get_block_start_patterns ( ) for i in range ( lineno , 0 , - 1 ) : match = pattern . search ( lines . get_line ( i ) ) if match is not None and count_line_indents ( lines . get_line ( i ) ) <= maximum_indents : striped = match . string . lstrip ( ) if i > 1 and striped . startswith ( 'if' ) or striped . startswith ( 'for' ) : bracs = 0 for j in range ( i , min ( i + 5 , lines . length ( ) + 1 ) ) : for c in lines . get_line ( j ) : if c == '#' : break if c in '[(' : bracs += 1 if c in ')]' : bracs -= 1 if bracs < 0 : break if bracs < 0 : break if bracs < 0 : continue return i return 1 | Approximate block start |
16,917 | def _init_logicals ( self ) : size = self . lines . length ( ) + 1 self . _starts = [ None ] * size self . _ends = [ None ] * size for start , end in self . _generate ( self . lines ) : self . _starts [ start ] = True self . _ends [ end ] = True | Should initialize _starts and _ends attributes |
16,918 | def create_move ( project , resource , offset = None ) : if offset is None : return MoveModule ( project , resource ) this_pymodule = project . get_pymodule ( resource ) pyname = evaluate . eval_location ( this_pymodule , offset ) if pyname is not None : pyobject = pyname . get_object ( ) if isinstance ( pyobject , pyobjects . PyModule ) or isinstance ( pyobject , pyobjects . PyPackage ) : return MoveModule ( project , pyobject . get_resource ( ) ) if isinstance ( pyobject , pyobjects . PyFunction ) and isinstance ( pyobject . parent , pyobjects . PyClass ) : return MoveMethod ( project , resource , offset ) if isinstance ( pyobject , pyobjects . PyDefinedObject ) and isinstance ( pyobject . parent , pyobjects . PyModule ) or isinstance ( pyname , pynames . AssignedName ) : return MoveGlobal ( project , resource , offset ) raise exceptions . RefactoringError ( 'Move only works on global classes/functions/variables, modules and ' 'methods.' ) | A factory for creating Move objects |
16,919 | def get_changes ( self , dest_attr , new_name = None , resources = None , task_handle = taskhandle . NullTaskHandle ( ) ) : changes = ChangeSet ( 'Moving method <%s>' % self . method_name ) if resources is None : resources = self . project . get_python_files ( ) if new_name is None : new_name = self . get_method_name ( ) resource1 , start1 , end1 , new_content1 = self . _get_changes_made_by_old_class ( dest_attr , new_name ) collector1 = codeanalyze . ChangeCollector ( resource1 . read ( ) ) collector1 . add_change ( start1 , end1 , new_content1 ) resource2 , start2 , end2 , new_content2 = self . _get_changes_made_by_new_class ( dest_attr , new_name ) if resource1 == resource2 : collector1 . add_change ( start2 , end2 , new_content2 ) else : collector2 = codeanalyze . ChangeCollector ( resource2 . read ( ) ) collector2 . add_change ( start2 , end2 , new_content2 ) result = collector2 . get_changed ( ) import_tools = importutils . ImportTools ( self . project ) new_imports = self . _get_used_imports ( import_tools ) if new_imports : goal_pymodule = libutils . get_string_module ( self . project , result , resource2 ) result = _add_imports_to_module ( import_tools , goal_pymodule , new_imports ) if resource2 in resources : changes . add_change ( ChangeContents ( resource2 , result ) ) if resource1 in resources : changes . add_change ( ChangeContents ( resource1 , collector1 . get_changed ( ) ) ) return changes | Return the changes needed for this refactoring |
16,920 | def get_kind ( self ) : scope = self . parent . get_scope ( ) if isinstance ( self . parent , PyClass ) : for decorator in self . decorators : pyname = rope . base . evaluate . eval_node ( scope , decorator ) if pyname == rope . base . builtins . builtins [ 'staticmethod' ] : return 'staticmethod' if pyname == rope . base . builtins . builtins [ 'classmethod' ] : return 'classmethod' return 'method' return 'function' | Get function type |
16,921 | def walk ( node , walker ) : method_name = '_' + node . __class__ . __name__ method = getattr ( walker , method_name , None ) if method is not None : if isinstance ( node , _ast . ImportFrom ) and node . module is None : node . module = '' return method ( node ) for child in get_child_nodes ( node ) : walk ( child , walker ) | Walk the syntax tree |
16,922 | def call_for_nodes ( node , callback , recursive = False ) : result = callback ( node ) if recursive and not result : for child in get_child_nodes ( node ) : call_for_nodes ( child , callback , recursive ) | If callback returns True the child nodes are skipped |
16,923 | def _realpath ( path ) : if sys . platform == 'cygwin' : if path [ 1 : 3 ] == ':\\' : return path elif path [ 1 : 3 ] == ':/' : path = "/cygdrive/" + path [ 0 ] + path [ 2 : ] return os . path . abspath ( os . path . expanduser ( path ) ) return os . path . realpath ( os . path . abspath ( os . path . expanduser ( path ) ) ) | Return the real path of path |
16,924 | def get_resource ( self , resource_name ) : path = self . _get_resource_path ( resource_name ) if not os . path . exists ( path ) : raise exceptions . ResourceNotFoundError ( 'Resource <%s> does not exist' % resource_name ) elif os . path . isfile ( path ) : return File ( self , resource_name ) elif os . path . isdir ( path ) : return Folder ( self , resource_name ) else : raise exceptions . ResourceNotFoundError ( 'Unknown resource ' + resource_name ) | Get a resource in a project . |
16,925 | def get_module ( self , name , folder = None ) : pymod = self . pycore . builtin_module ( name ) if pymod is not None : return pymod module = self . find_module ( name , folder ) if module is None : raise ModuleNotFoundError ( 'Module %s not found' % name ) return self . pycore . resource_to_pyobject ( module ) | Returns a PyObject if the module was found . |
16,926 | def get_source_folders ( self ) : if self . root is None : return [ ] result = list ( self . _custom_source_folders ) result . extend ( self . pycore . _find_source_folders ( self . root ) ) return result | Returns project source folders |
16,927 | def validate ( self , folder ) : for observer in list ( self . observers ) : observer . validate ( folder ) | Validate files and folders contained in this folder |
16,928 | def do ( self , changes , task_handle = taskhandle . NullTaskHandle ( ) ) : self . history . do ( changes , task_handle = task_handle ) | Apply the changes in a ChangeSet |
16,929 | def find_module ( self , modname , folder = None ) : for src in self . get_source_folders ( ) : module = _find_module_in_folder ( src , modname ) if module is not None : return module for src in self . get_python_path_folders ( ) : module = _find_module_in_folder ( src , modname ) if module is not None : return module if folder is not None : module = _find_module_in_folder ( folder , modname ) if module is not None : return module return None | Returns a resource corresponding to the given module |
16,930 | def get_python_files ( self ) : return [ resource for resource in self . get_files ( ) if self . pycore . is_python_file ( resource ) ] | Returns all python files available in the project |
16,931 | def get_objects ( self ) : return rope . base . oi . soi . get_passed_objects ( self . pyfunction , self . index ) | Returns the list of objects passed as this parameter |
16,932 | 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 | Get a project to changes dict |
16,933 | def saveit ( func ) : name = '_' + func . __name__ def _wrapper ( self , * args , ** kwds ) : if not hasattr ( self , name ) : setattr ( self , name , func ( self , * args , ** kwds ) ) return getattr ( self , name ) return _wrapper | A decorator that caches the return value of a function |
16,934 | def prevent_recursion ( default ) : def decorator ( func ) : name = '_calling_%s_' % func . __name__ def newfunc ( self , * args , ** kwds ) : if getattr ( self , name , False ) : return default ( ) setattr ( self , name , True ) try : return func ( self , * args , ** kwds ) finally : setattr ( self , name , False ) return newfunc return decorator | A decorator that returns the return value of default in recursions |
16,935 | def ignore_exception ( exception_class ) : def _decorator ( func ) : def newfunc ( * args , ** kwds ) : try : return func ( * args , ** kwds ) except exception_class : pass return newfunc return _decorator | A decorator that ignores exception_class exceptions |
16,936 | def deprecated ( message = None ) : def _decorator ( func , message = message ) : if message is None : message = '%s is deprecated' % func . __name__ def newfunc ( * args , ** kwds ) : warnings . warn ( message , DeprecationWarning , stacklevel = 2 ) return func ( * args , ** kwds ) return newfunc return _decorator | A decorator for deprecated functions |
16,937 | def cached ( size ) : def decorator ( func ) : cached_func = _Cached ( func , size ) return lambda * a , ** kw : cached_func ( * a , ** kw ) return decorator | A caching decorator based on parameter objects |
16,938 | def resolve ( str_or_obj ) : from rope . base . utils . pycompat import string_types if not isinstance ( str_or_obj , string_types ) : return str_or_obj if '.' not in str_or_obj : str_or_obj += '.' mod_name , obj_name = str_or_obj . rsplit ( '.' , 1 ) __import__ ( mod_name ) mod = sys . modules [ mod_name ] return getattr ( mod , obj_name ) if obj_name else mod | Returns object from string |
16,939 | def _find_primary_without_dot_start ( self , offset ) : last_atom = offset offset = self . _find_last_non_space_char ( last_atom ) while offset > 0 and self . code [ offset ] in ')]' : last_atom = self . _find_parens_start ( offset ) offset = self . _find_last_non_space_char ( last_atom - 1 ) if offset >= 0 and ( self . code [ offset ] in '"\'})]' or self . _is_id_char ( offset ) ) : atom_start = self . _find_atom_start ( offset ) if not keyword . iskeyword ( self . code [ atom_start : offset + 1 ] ) : return atom_start return last_atom | It tries to find the undotted primary start |
16,940 | def get_splitted_primary_before ( self , offset ) : if offset == 0 : return ( '' , '' , 0 ) end = offset - 1 word_start = self . _find_atom_start ( end ) real_start = self . _find_primary_start ( end ) if self . code [ word_start : offset ] . strip ( ) == '' : word_start = end if self . code [ end ] . isspace ( ) : word_start = end if self . code [ real_start : word_start ] . strip ( ) == '' : real_start = word_start if real_start == word_start == end and not self . _is_id_char ( end ) : return ( '' , '' , offset ) if real_start == word_start : return ( '' , self . raw [ word_start : offset ] , word_start ) else : if self . code [ end ] == '.' : return ( self . raw [ real_start : end ] , '' , offset ) last_dot_position = word_start if self . code [ word_start ] != '.' : last_dot_position = self . _find_last_non_space_char ( word_start - 1 ) last_char_position = self . _find_last_non_space_char ( last_dot_position - 1 ) if self . code [ word_start ] . isspace ( ) : word_start = offset return ( self . raw [ real_start : last_char_position + 1 ] , self . raw [ word_start : offset ] , word_start ) | returns expression starting starting_offset |
16,941 | def create_inline ( project , resource , offset ) : pyname = _get_pyname ( project , resource , offset ) message = 'Inline refactoring should be performed on ' 'a method, local variable or parameter.' if pyname is None : raise rope . base . exceptions . RefactoringError ( message ) if isinstance ( pyname , pynames . ImportedName ) : pyname = pyname . _get_imported_pyname ( ) if isinstance ( pyname , pynames . AssignedName ) : return InlineVariable ( project , resource , offset ) if isinstance ( pyname , pynames . ParameterName ) : return InlineParameter ( project , resource , offset ) if isinstance ( pyname . get_object ( ) , pyobjects . PyFunction ) : return InlineMethod ( project , resource , offset ) else : raise rope . base . exceptions . RefactoringError ( message ) | Create a refactoring object for inlining |
16,942 | 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 resource |
16,943 | 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 ) | Get the imported PyModule |
16,944 | def code_assist ( project , source_code , offset , resource = None , templates = None , maxfixes = 1 , later_locals = True ) : if templates is not None : warnings . warn ( 'Codeassist no longer supports templates' , DeprecationWarning , stacklevel = 2 ) assist = _PythonCodeAssist ( project , source_code , offset , resource = resource , maxfixes = maxfixes , later_locals = later_locals ) return assist ( ) | Return python code completions as a list of CodeAssistProposal \ s |
16,945 | def starting_offset ( source_code , offset ) : word_finder = worder . Worder ( source_code , True ) expression , starting , starting_offset = word_finder . get_splitted_primary_before ( offset ) return starting_offset | Return the offset in which the completion should be inserted |
16,946 | def get_doc ( project , source_code , offset , resource = None , maxfixes = 1 ) : fixer = fixsyntax . FixSyntax ( project , source_code , resource , maxfixes ) pyname = fixer . pyname_at ( offset ) if pyname is None : return None pyobject = pyname . get_object ( ) return PyDocExtractor ( ) . get_doc ( pyobject ) | Get the pydoc |
16,947 | def get_calltip ( project , source_code , offset , resource = None , maxfixes = 1 , ignore_unknown = False , remove_self = False ) : fixer = fixsyntax . FixSyntax ( project , source_code , resource , maxfixes ) pyname = fixer . pyname_at ( offset ) if pyname is None : return None pyobject = pyname . get_object ( ) return PyDocExtractor ( ) . get_calltip ( pyobject , ignore_unknown , remove_self ) | Get the calltip of a function |
16,948 | def get_canonical_path ( project , resource , offset ) : pymod = project . get_pymodule ( resource ) pyname = rope . base . evaluate . eval_location ( pymod , offset ) defmod , lineno = pyname . get_definition_location ( ) if not defmod : return None scope = defmod . get_scope ( ) . get_inner_scope_for_line ( lineno ) names = [ ] if isinstance ( pyname , pynamesdef . ParameterName ) : names = [ ( worder . get_name_at ( pymod . get_resource ( ) , offset ) , 'PARAMETER' ) ] elif isinstance ( pyname , pynamesdef . AssignedName ) : names = [ ( worder . get_name_at ( pymod . get_resource ( ) , offset ) , 'VARIABLE' ) ] while scope . parent : if isinstance ( scope , pyscopes . FunctionScope ) : scope_type = 'FUNCTION' elif isinstance ( scope , pyscopes . ClassScope ) : scope_type = 'CLASS' else : scope_type = None names . append ( ( scope . pyobject . get_name ( ) , scope_type ) ) scope = scope . parent names . append ( ( defmod . get_resource ( ) . real_path , 'MODULE' ) ) names . reverse ( ) return names | Get the canonical path to an object . |
16,949 | def sorted_proposals ( proposals , scopepref = None , typepref = None ) : sorter = _ProposalSorter ( proposals , scopepref , typepref ) return sorter . get_sorted_proposal_list ( ) | Sort a list of proposals |
16,950 | def starting_expression ( source_code , offset ) : word_finder = worder . Worder ( source_code , True ) expression , starting , starting_offset = word_finder . get_splitted_primary_before ( offset ) if expression : return expression + '.' + starting return starting | Return the expression to complete |
16,951 | def parameters ( self ) : pyname = self . pyname if isinstance ( pyname , pynames . ImportedName ) : pyname = pyname . _get_imported_pyname ( ) if isinstance ( pyname , pynames . DefinedName ) : pyobject = pyname . get_object ( ) if isinstance ( pyobject , pyobjects . AbstractFunction ) : return pyobject . get_param_names ( ) | The names of the parameters the function takes . |
16,952 | def get_doc ( self ) : if not self . pyname : return None pyobject = self . pyname . get_object ( ) if not hasattr ( pyobject , 'get_doc' ) : return None return self . pyname . get_object ( ) . get_doc ( ) | Get the proposed object s docstring . |
16,953 | def get_default ( self ) : definfo = functionutils . DefinitionInfo . read ( self . _function ) for arg , default in definfo . args_with_defaults : if self . argname == arg : return default return None | Get a string representation of a param s default value . |
16,954 | def get_sorted_proposal_list ( self ) : proposals = { } for proposal in self . proposals : proposals . setdefault ( proposal . scope , [ ] ) . append ( proposal ) result = [ ] for scope in self . scopepref : scope_proposals = proposals . get ( scope , [ ] ) scope_proposals = [ proposal for proposal in scope_proposals if proposal . type in self . typerank ] scope_proposals . sort ( key = self . _proposal_key ) result . extend ( scope_proposals ) return result | Return a list of CodeAssistProposal |
16,955 | def set_prefs ( prefs ) : prefs [ 'ignored_resources' ] = [ '*.pyc' , '*~' , '.ropeproject' , '.hg' , '.svn' , '_svn' , '.git' , '.tox' ] prefs [ 'save_objectdb' ] = True prefs [ 'compress_objectdb' ] = False prefs [ 'automatic_soa' ] = True prefs [ 'soa_followed_calls' ] = 0 prefs [ 'perform_doa' ] = True prefs [ 'validate_objectdb' ] = True prefs [ 'max_history_items' ] = 32 prefs [ 'save_history' ] = True prefs [ 'compress_history' ] = False prefs [ 'indent_size' ] = 4 prefs [ 'extension_modules' ] = [ ] prefs [ 'import_dynload_stdmods' ] = True prefs [ 'ignore_syntax_errors' ] = False prefs [ 'ignore_bad_imports' ] = False prefs [ 'prefer_module_from_imports' ] = False prefs [ 'split_imports' ] = False prefs [ 'pull_imports_to_top' ] = True prefs [ 'sort_imports_alphabetically' ] = False prefs [ 'type_hinting_factory' ] = ( 'rope.base.oi.type_hinting.factory.default_type_hinting_factory' ) | This function is called before opening the project |
16,956 | def resource_moved ( self , resource , new_resource ) : if self . moved is not None : self . moved ( resource , new_resource ) | It is called when a resource is moved |
16,957 | def add_resource ( self , resource ) : if resource . exists ( ) : self . resources [ resource ] = self . timekeeper . get_indicator ( resource ) else : self . resources [ resource ] = None | Add a resource to the list of interesting resources |
16,958 | def get_indicator ( self , resource ) : path = resource . real_path if os . name != 'posix' and os . path . isdir ( path ) : return ( os . path . getmtime ( path ) , len ( os . listdir ( path ) ) , os . path . getsize ( path ) ) return ( os . path . getmtime ( path ) , os . path . getsize ( path ) ) | Return the modification time and size of a Resource . |
16,959 | def path_to_resource ( project , path , type = None ) : project_path = path_relative_to_project_root ( project , path ) if project_path is None : project_path = rope . base . project . _realpath ( path ) project = rope . base . project . get_no_project ( ) if type is None : return project . get_resource ( project_path ) if type == 'file' : return project . get_file ( project_path ) if type == 'folder' : return project . get_folder ( project_path ) return None | Get the resource at path |
16,960 | def report_change ( project , path , old_content ) : resource = path_to_resource ( project , path ) if resource is None : return for observer in list ( project . observers ) : observer . resource_changed ( resource ) if project . pycore . automatic_soa : rope . base . pycore . perform_soa_on_changed_scopes ( project , resource , old_content ) | Report that the contents of file at path was changed |
16,961 | def analyze_modules ( project , task_handle = taskhandle . NullTaskHandle ( ) ) : resources = project . get_python_files ( ) job_set = task_handle . create_jobset ( 'Analyzing Modules' , len ( resources ) ) for resource in resources : job_set . started_job ( resource . path ) analyze_module ( project , resource ) job_set . finished_job ( ) | Perform static object analysis on all python files in the project |
16,962 | 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_info , "module_name" ) : new_import = importinfo . FromImport ( import_info . module_name , import_info . level , [ name_and_alias ] ) else : new_import = importinfo . NormalImport ( [ name_and_alias ] ) self . add_import ( new_import ) import_stmt . empty_import ( ) | force a single import per statement |
16,963 | 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 ) | Removes pyname when imported in from mod import x |
16,964 | def create_arguments ( primary , pyfunction , call_node , scope ) : args = list ( call_node . args ) args . extend ( call_node . keywords ) called = call_node . func if _is_method_call ( primary , pyfunction ) and isinstance ( called , ast . Attribute ) : args . insert ( 0 , called . value ) return Arguments ( args , scope ) | A factory for creating Arguments |
16,965 | def set ( self , key , value ) : if key in self . callbacks : self . callbacks [ key ] ( value ) else : self . prefs [ key ] = value | Set the value of key preference to value . |
16,966 | def add ( self , key , value ) : if not key in self . prefs : self . prefs [ key ] = [ ] self . prefs [ key ] . append ( value ) | Add an entry to a list preference |
16,967 | def fix_indentation ( code , new_indents ) : min_indents = find_minimum_indents ( code ) return indent_lines ( code , new_indents - min_indents ) | Change the indentation of code to new_indents |
16,968 | def get_body ( pyfunction ) : pymodule = pyfunction . get_module ( ) start , end = get_body_region ( pyfunction ) return fix_indentation ( pymodule . source_code [ start : end ] , 0 ) | Return unindented function body |
16,969 | def get_body_region ( defined ) : scope = defined . get_scope ( ) pymodule = defined . get_module ( ) lines = pymodule . lines node = defined . get_ast ( ) start_line = node . lineno if defined . get_doc ( ) is None : start_line = node . body [ 0 ] . lineno elif len ( node . body ) > 1 : start_line = node . body [ 1 ] . lineno start = lines . get_line_start ( start_line ) scope_start = pymodule . logical_lines . logical_line_in ( scope . start ) if scope_start [ 1 ] >= start_line : start = pymodule . source_code . index ( ':' , start ) + 1 while pymodule . source_code [ start ] . isspace ( ) : start += 1 end = min ( lines . get_line_end ( scope . end ) + 1 , len ( pymodule . source_code ) ) return start , end | Return the start and end offsets of function body |
16,970 | def do ( self , changes , task_handle = taskhandle . NullTaskHandle ( ) ) : try : self . current_change = changes changes . do ( change . create_job_set ( task_handle , changes ) ) finally : self . current_change = None if self . _is_change_interesting ( changes ) : self . undo_list . append ( changes ) self . _remove_extra_items ( ) del self . redo_list [ : ] | Perform the change and add it to the self . undo_list |
16,971 | def undo ( self , change = None , drop = False , task_handle = taskhandle . NullTaskHandle ( ) ) : if not self . _undo_list : raise exceptions . HistoryError ( 'Undo list is empty' ) if change is None : change = self . undo_list [ - 1 ] dependencies = self . _find_dependencies ( self . undo_list , change ) self . _move_front ( self . undo_list , dependencies ) self . _perform_undos ( len ( dependencies ) , task_handle ) result = self . redo_list [ - len ( dependencies ) : ] if drop : del self . redo_list [ - len ( dependencies ) : ] return result | Redo done changes from the history |
16,972 | def redo ( self , change = None , task_handle = taskhandle . NullTaskHandle ( ) ) : if not self . redo_list : raise exceptions . HistoryError ( 'Redo list is empty' ) if change is None : change = self . redo_list [ - 1 ] dependencies = self . _find_dependencies ( self . redo_list , change ) self . _move_front ( self . redo_list , dependencies ) self . _perform_redos ( len ( dependencies ) , task_handle ) return self . undo_list [ - len ( dependencies ) : ] | Redo undone changes from the history |
16,973 | def get_string_scope ( self , code , resource = None ) : return rope . base . libutils . get_string_scope ( code , resource ) | Returns a Scope object for the given code |
16,974 | def run_module ( self , resource , args = None , stdin = None , stdout = None ) : perform_doa = self . project . prefs . get ( 'perform_doi' , True ) perform_doa = self . project . prefs . get ( 'perform_doa' , perform_doa ) receiver = self . object_info . doa_data_received if not perform_doa : receiver = None runner = rope . base . oi . doa . PythonFileRunner ( self , resource , args , stdin , stdout , receiver ) runner . add_finishing_observer ( self . module_cache . forget_all_data ) runner . run ( ) return runner | Run resource module |
16,975 | def analyze_module ( self , resource , should_analyze = lambda py : True , search_subscopes = lambda py : True , followed_calls = None ) : if followed_calls is None : followed_calls = self . project . prefs . get ( 'soa_followed_calls' , 0 ) pymodule = self . resource_to_pyobject ( resource ) self . module_cache . forget_all_data ( ) rope . base . oi . soa . analyze_module ( self , pymodule , should_analyze , search_subscopes , followed_calls ) | Analyze resource module for static object inference |
16,976 | def is_changed ( self , start , end ) : left , right = self . _get_changed ( start , end ) if left < right : return True return False | Tell whether any of start till end lines have changed |
16,977 | def consume_changes ( self , start , end ) : left , right = self . _get_changed ( start , end ) if left < right : del self . lines [ left : right ] return left < right | Clear the changed status of lines from start till end |
16,978 | def get_name ( self , name ) : if name not in self . get_names ( ) : raise exceptions . NameNotFoundError ( 'name %s not found' % name ) return self . get_names ( ) [ name ] | Return name PyName defined in this scope |
16,979 | def get_modules ( self , name ) : result = [ ] for module in self . names : if name in self . names [ module ] : result . append ( module ) return result | Return the list of modules that have global name |
16,980 | def get_all_names ( self ) : result = set ( ) for module in self . names : result . update ( set ( self . names [ module ] ) ) return result | Return the list of all cached global names |
16,981 | def generate_cache ( self , resources = None , underlined = None , task_handle = taskhandle . NullTaskHandle ( ) ) : if resources is None : resources = self . project . get_python_files ( ) job_set = task_handle . create_jobset ( 'Generatig autoimport cache' , len ( resources ) ) for file in resources : job_set . started_job ( 'Working on <%s>' % file . path ) self . update_resource ( file , underlined ) job_set . finished_job ( ) | Generate global name cache for project files |
16,982 | def generate_modules_cache ( self , modules , underlined = None , task_handle = taskhandle . NullTaskHandle ( ) ) : job_set = task_handle . create_jobset ( 'Generatig autoimport cache for modules' , len ( modules ) ) for modname in modules : job_set . started_job ( 'Working on <%s>' % modname ) if modname . endswith ( '.*' ) : mod = self . project . find_module ( modname [ : - 2 ] ) if mod : for sub in submodules ( mod ) : self . update_resource ( sub , underlined ) else : self . update_module ( modname , underlined ) job_set . finished_job ( ) | Generate global name cache for modules listed in modules |
16,983 | def find_insertion_line ( self , code ) : match = re . search ( r'^(def|class)\s+' , code ) if match is not None : code = code [ : match . start ( ) ] try : pymodule = libutils . get_string_module ( self . project , code ) except exceptions . ModuleSyntaxError : return 1 testmodname = '__rope_testmodule_rope' importinfo = importutils . NormalImport ( ( ( testmodname , None ) , ) ) module_imports = importutils . get_module_imports ( self . project , pymodule ) module_imports . add_import ( importinfo ) code = module_imports . get_changed_source ( ) offset = code . index ( testmodname ) lineno = code . count ( '\n' , 0 , offset ) + 1 return lineno | Guess at what line the new import should be inserted |
16,984 | def update_resource ( self , resource , underlined = None ) : try : pymodule = self . project . get_pymodule ( resource ) modname = self . _module_name ( resource ) self . _add_names ( pymodule , modname , underlined ) except exceptions . ModuleSyntaxError : pass | Update the cache for global names in resource |
16,985 | def update_module ( self , modname , underlined = None ) : try : pymodule = self . project . get_module ( modname ) self . _add_names ( pymodule , modname , underlined ) except exceptions . ModuleNotFoundError : pass | Update the cache for global names in modname module |
16,986 | def replace ( code , pattern , goal ) : finder = similarfinder . RawSimilarFinder ( code ) matches = list ( finder . get_matches ( pattern ) ) ast = patchedast . get_patched_ast ( code ) lines = codeanalyze . SourceLinesAdapter ( code ) template = similarfinder . CodeTemplate ( goal ) computer = _ChangeComputer ( code , ast , lines , template , matches ) result = computer . get_changed ( ) if result is None : return code return result | used by other refactorings |
16,987 | 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 . _pydefined_to_str ( value ) if imports is not None : warnings . warn ( 'The use of imports parameter is deprecated; ' 'use imports parameter of the constructor, instead.' , DeprecationWarning , stacklevel = 2 ) self . imports = imports changes = change . ChangeSet ( 'Restructuring <%s> to <%s>' % ( self . pattern , self . goal ) ) if resources is not None : files = [ resource for resource in resources if libutils . is_python_file ( self . project , resource ) ] else : files = self . project . get_python_files ( ) job_set = task_handle . create_jobset ( 'Collecting Changes' , len ( files ) ) for resource in files : job_set . started_job ( resource . path ) pymodule = self . project . get_pymodule ( resource ) finder = similarfinder . SimilarFinder ( pymodule , wildcards = self . wildcards ) matches = list ( finder . get_matches ( self . pattern , self . args ) ) computer = self . _compute_changes ( matches , pymodule ) result = computer . get_changed ( ) if result is not None : imported_source = self . _add_imports ( resource , result , self . imports ) changes . add_change ( change . ChangeContents ( resource , imported_source ) ) job_set . finished_job ( ) return changes | Get the changes needed by this restructuring |
16,988 | 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 | Convert str to str dicts to str to PyObject dicts |
16,989 | def returned ( self ) : if self . _returned is None : node = _parse_text ( self . extracted ) self . _returned = usefunction . _returns_last ( node ) return self . _returned | Does the extracted piece contain return statement |
16,990 | def get_pymodule ( self ) : msg = None code = self . code tries = 0 while True : try : if tries == 0 and self . resource is not None and self . resource . read ( ) == code : return self . project . get_pymodule ( self . resource , force_errors = True ) return libutils . get_string_module ( self . project , code , resource = self . resource , force_errors = True ) except exceptions . ModuleSyntaxError as e : if msg is None : msg = '%s:%s %s' % ( e . filename , e . lineno , e . message_ ) if tries < self . maxfixes : tries += 1 self . commenter . comment ( e . lineno ) code = '\n' . join ( self . commenter . lines ) else : raise exceptions . ModuleSyntaxError ( e . filename , e . lineno , 'Failed to fix error: {0}' . format ( msg ) ) | Get a PyModule |
16,991 | def _handle_job_set ( function ) : def call ( self , job_set = taskhandle . NullJobSet ( ) ) : job_set . started_job ( str ( self ) ) function ( self ) job_set . finished_job ( ) return call | A decorator for handling taskhandle . JobSet \ s |
16,992 | def count_changes ( change ) : if isinstance ( change , ChangeSet ) : result = 0 for child in change . changes : result += count_changes ( child ) return result return 1 | Counts the number of basic changes a Change will make |
16,993 | def analyze_module ( pycore , pymodule , should_analyze , search_subscopes , followed_calls ) : _analyze_node ( pycore , pymodule , should_analyze , search_subscopes , followed_calls ) | Analyze pymodule for static object inference |
16,994 | 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 ) | Get changes caused by this refactoring |
16,995 | def get_changes ( self , fixer = str . lower , task_handle = taskhandle . NullTaskHandle ( ) ) : stack = changestack . ChangeStack ( self . project , 'Fixing module names' ) jobset = task_handle . create_jobset ( 'Fixing module names' , self . _count_fixes ( fixer ) + 1 ) try : while True : for resource in self . _tobe_fixed ( fixer ) : jobset . started_job ( resource . path ) renamer = rename . Rename ( self . project , resource ) changes = renamer . get_changes ( fixer ( self . _name ( resource ) ) ) stack . push ( changes ) jobset . finished_job ( ) break else : break finally : jobset . started_job ( 'Reverting to original state' ) stack . pop_all ( ) jobset . finished_job ( ) return stack . merged ( ) | Fix module names |
16,996 | def infer_returned_object ( pyfunction , args ) : object_info = pyfunction . pycore . object_info result = object_info . get_exact_returned ( pyfunction , args ) if result is not None : return result result = _infer_returned ( pyfunction , args ) if result is not None : if args and pyfunction . get_module ( ) . get_resource ( ) is not None : params = args . get_arguments ( pyfunction . get_param_names ( special_args = False ) ) object_info . function_called ( pyfunction , params , result ) return result result = object_info . get_returned ( pyfunction , args ) if result is not None : return result hint_return = get_type_hinting_factory ( pyfunction . pycore . project ) . make_return_provider ( ) type_ = hint_return ( pyfunction ) if type_ is not None : return rope . base . pyobjects . PyObject ( type_ ) | Infer the PyObject this PyFunction returns after calling |
16,997 | def infer_parameter_objects ( pyfunction ) : object_info = pyfunction . pycore . object_info result = object_info . get_parameter_objects ( pyfunction ) if result is None : result = _parameter_objects ( pyfunction ) _handle_first_parameter ( pyfunction , result ) return result | Infer the PyObject \ s of parameters of this PyFunction |
16,998 | def normalize_so_name ( name ) : if "cpython" in name : return os . path . splitext ( os . path . splitext ( name ) [ 0 ] ) [ 0 ] if name == "timemodule.so" : return "time" return os . path . splitext ( name ) [ 0 ] | Handle different types of python installations |
16,999 | def run ( self ) : env = dict ( os . environ ) file_path = self . file . real_path path_folders = self . pycore . project . get_source_folders ( ) + self . pycore . project . get_python_path_folders ( ) env [ 'PYTHONPATH' ] = os . pathsep . join ( folder . real_path for folder in path_folders ) runmod_path = self . pycore . project . find_module ( 'rope.base.oi.runmod' ) . real_path self . receiver = None self . _init_data_receiving ( ) send_info = '-' if self . receiver : send_info = self . receiver . get_send_info ( ) args = [ sys . executable , runmod_path , send_info , self . pycore . project . address , self . file . real_path ] if self . analyze_data is None : del args [ 1 : 4 ] if self . args is not None : args . extend ( self . args ) self . process = subprocess . Popen ( executable = sys . executable , args = args , env = env , cwd = os . path . split ( file_path ) [ 0 ] , stdin = self . stdin , stdout = self . stdout , stderr = self . stdout , close_fds = os . name != 'nt' ) | Execute the process |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.