INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a list of menu actions
def get_menu_actions(self): """Returns a list of menu actions""" items = self.selectedItems() actions = self.get_actions_from_items(items) if actions: actions.append(None) actions += self.common_actions return actions
Item selection has changed
def item_selection_changed(self): """Item selection has changed""" is_selection = len(self.selectedItems()) > 0 self.expand_selection_action.setEnabled(is_selection) self.collapse_selection_action.setEnabled(is_selection)
Return items ( excluding top level items )
def get_items(self): """Return items (excluding top level items)""" itemlist = [] def add_to_itemlist(item): for index in range(item.childCount()): citem = item.child(index) itemlist.append(citem) add_to_itemlist(citem) ...
Save all items expanded state
def save_expanded_state(self): """Save all items expanded state""" self.__expanded_state = {} def add_to_state(item): user_text = get_item_user_text(item) self.__expanded_state[hash(user_text)] = item.isExpanded() def browse_children(item): add_...
Restore all items expanded state
def restore_expanded_state(self): """Restore all items expanded state""" if self.__expanded_state is None: return for item in self.get_items()+self.get_top_level_items(): user_text = get_item_user_text(item) is_expanded = self.__expanded_state.get(hash(u...
Sorting tree wrt top level items
def sort_top_level_items(self, key): """Sorting tree wrt top level items""" self.save_expanded_state() items = sorted([self.takeTopLevelItem(0) for index in range(self.topLevelItemCount())], key=key) for index, item in enumerate(items): self.inse...
Override Qt method
def contextMenuEvent(self, event): """Override Qt method""" self.update_menu() self.menu.popup(event.globalPos())
Returns a list containing the names of all the modules available in the standard library. Based on the function get_root_modules from the IPython project. Present in IPython. core. completerlib in v0. 13. 1 Copyright ( C ) 2010 - 2011 The IPython Development Team. Distributed under the terms of the BSD License.
def get_stdlib_modules(): """ Returns a list containing the names of all the modules available in the standard library. Based on the function get_root_modules from the IPython project. Present in IPython.core.completerlib in v0.13.1 Copyright (C) 2010-2011 The IPython Development Team....
Prints the editor fold tree to stdout for debugging purpose.
def print_tree(editor, file=sys.stdout, print_blocks=False, return_list=False): """ Prints the editor fold tree to stdout, for debugging purpose. :param editor: CodeEditor instance. :param file: file handle where the tree will be printed. Default is stdout. :param print_blocks: True to print all bl...
Dict -- > Dict of lists
def envdict2listdict(envdict): """Dict --> Dict of lists""" sep = os.path.pathsep for key in envdict: if sep in envdict[key]: envdict[key] = [path.strip() for path in envdict[key].split(sep)] return envdict
Dict of lists -- > Dict
def listdict2envdict(listdict): """Dict of lists --> Dict""" for key in listdict: if isinstance(listdict[key], list): listdict[key] = os.path.pathsep.join(listdict[key]) return listdict
Run Windows environment variable editor
def main(): """Run Windows environment variable editor""" from spyder.utils.qthelpers import qapplication app = qapplication() if os.name == 'nt': dialog = WinUserEnvDialog() else: dialog = EnvDialog() dialog.show() app.exec_()
Qt override.
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: self._parent.process_text() if self._parent.is_valid(): self._parent.keyPressEvent(event) else: QLineEdit.keyPressEve...
Qt override. This is needed to be able to intercept the Tab key press event.
def event(self, event): """ Qt override. This is needed to be able to intercept the Tab key press event. """ if event.type() == QEvent.KeyPress: if (event.key() == Qt.Key_Tab or event.key() == Qt.Key_Space): text = self.text() ...
Qt override.
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: QTableWidget.keyPressEvent(self, event) # To avoid having to enter one final tab self.setDisabled(True) self.setDisabled(False) ...
Update the column and row numbering in the headers.
def reset_headers(self): """ Update the column and row numbering in the headers. """ rows = self.rowCount() cols = self.columnCount() for r in range(rows): self.setVerticalHeaderItem(r, QTableWidgetItem(str(r))) for c in range(cols): ...
Return the entered array in a parseable form.
def text(self): """ Return the entered array in a parseable form. """ text = [] rows = self.rowCount() cols = self.columnCount() # handle empty table case if rows == 2 and cols == 2: item = self.item(0, 0) if item is Non...
Qt override.
def keyPressEvent(self, event): """ Qt override. """ QToolTip.hideText() ctrl = event.modifiers() & Qt.ControlModifier if event.key() in [Qt.Key_Enter, Qt.Key_Return]: if ctrl: self.process_text(array=False) else: ...
Qt Override. Usefull when in line edit mode.
def event(self, event): """ Qt Override. Usefull when in line edit mode. """ if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab: return False return QWidget.event(self, event)
Construct the text based on the entered content in the widget.
def process_text(self, array=True): """ Construct the text based on the entered content in the widget. """ if array: prefix = 'np.array([[' else: prefix = 'np.matrix([[' suffix = ']])' values = self._widget.text().strip() ...
Updates the icon and tip based on the validity of the array content.
def update_warning(self): """ Updates the icon and tip based on the validity of the array content. """ widget = self._button_warning if not self.is_valid(): tip = _('Array dimensions not valid') widget.setIcon(ima.icon('MessageBoxWarning')) ...
Get selected language setting and save to language configuration file.
def _save_lang(self): """ Get selected language setting and save to language configuration file. """ for combobox, (option, _default) in list(self.comboboxes.items()): if option == 'interface_language': data = combobox.itemData(combobox.currentIndex()) ...
Check if path has write access
def is_writable(path): """Check if path has write access""" try: testfile = tempfile.TemporaryFile(dir=path) testfile.close() except OSError as e: if e.errno == errno.EACCES: # 13 return False return True
Get all available project types.
def _get_project_types(self): """Get all available project types.""" project_types = get_available_project_types() projects = [] for project in project_types: projects.append(project.PROJECT_TYPE_NAME) return projects
Select directory.
def select_location(self): """Select directory.""" location = osp.normpath(getexistingdirectory(self, _("Select directory"), self.location)) if location: if is_writable(l...
Update text of location.
def update_location(self, text=''): """Update text of location.""" self.text_project_name.setEnabled(self.radio_new_dir.isChecked()) name = self.text_project_name.text().strip() if name and self.radio_new_dir.isChecked(): path = osp.join(self.location, name) ...
Create project.
def create_project(self): """Create project.""" packages = ['python={0}'.format(self.combo_python_version.currentText())] self.sig_project_creation_requested.emit( self.text_location.text(), self.combo_project_type.currentText(), packages) self....
Set shell styles font
def set_font(self, font): """Set shell styles font""" self.setFont(font) self.set_pythonshell_font(font) cursor = self.textCursor() cursor.select(QTextCursor.Document) charformat = QTextCharFormat() charformat.setFontFamily(font.family()) charforma...
Setup shell context menu
def setup_context_menu(self): """Setup shell context menu""" self.menu = QMenu(self) self.cut_action = create_action(self, _("Cut"), shortcut=keybinding('Cut'), icon=ima.icon('editcut'), ...
Reimplement Qt method
def contextMenuEvent(self, event): """Reimplement Qt method""" state = self.has_selected_text() self.copy_action.setEnabled(state) self.cut_action.setEnabled(state) self.delete_action.setEnabled(state) self.menu.popup(event.globalPos()) event.accept()
Select current line ( without selecting console prompt )
def _select_input(self): """Select current line (without selecting console prompt)""" line, index = self.get_position('eof') if self.current_prompt_pos is None: pline, pindex = line, index else: pline, pindex = self.current_prompt_pos self.setSelect...
Set input buffer
def _set_input_buffer(self, text): """Set input buffer""" if self.current_prompt_pos is not None: self.replace_text(self.current_prompt_pos, 'eol', text) else: self.insert(text) self.set_cursor_position('eof')
Return input buffer
def _get_input_buffer(self): """Return input buffer""" input_buffer = '' if self.current_prompt_pos is not None: input_buffer = self.get_text(self.current_prompt_pos, 'eol') input_buffer = input_buffer.replace(os.linesep, '\n') return input_buffer
Print a new prompt and save its ( line index ) position
def new_prompt(self, prompt): """ Print a new prompt and save its (line, index) position """ if self.get_cursor_line_column()[1] != 0: self.write('\n') self.write(prompt, prompt=True) # now we update our cursor giving end of prompt self.current...
Check if selected text is r/ w otherwise remove read - only parts of selection
def check_selection(self): """ Check if selected text is r/w, otherwise remove read-only parts of selection """ if self.current_prompt_pos is None: self.set_cursor_position('eof') else: self.truncate_selection(self.current_prompt_pos)
Copy text to clipboard... or keyboard interrupt
def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.has_selected_text(): ConsoleBaseWidget.copy(self) elif not sys.platform == 'darwin': self.interrupt()
Save current history log ( all text in console )
def save_historylog(self): """Save current history log (all text in console)""" title = _("Save history log") self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, self.historylog_filename, "%s (*.log)" % _("History logs")) ...
On new input line
def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
Pre - process keypress event: return True if event is accepted false otherwise
def preprocess_keyevent(self, event): """Pre-process keypress event: return True if event is accepted, false otherwise""" # Copy must be done first to be able to copy read-only text parts # (otherwise, right below, we would remove selection # if not on current line) ...
Post - process keypress event: in InternalShell this is method is called when shell is ready
def postprocess_keyevent(self, event): """Post-process keypress event: in InternalShell, this is method is called when shell is ready""" event, text, key, ctrl, shift = restore_keyevent(event) # Is cursor on the last line? and after prompt? if len(text): ...
Load history from a. py file in user home directory
def load_history(self): """Load history from a .py file in user home directory""" if osp.isfile(self.history_filename): rawhistory, _ = encoding.readlines(self.history_filename) rawhistory = [line.replace('\n', '') for line in rawhistory] if rawhistory[1] != self...
Simulate stderr
def write_error(self, text): """Simulate stderr""" self.flush() self.write(text, flush=True, error=True) if get_debug_level(): STDERR.write(text)
Simulate stdout and stderr
def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test is useful to discriminate QStrings from decoded str text = to_text_string(text) self.__bu...
Flush buffer write text to console
def flush(self, error=False, prompt=False): """Flush buffer, write text to console""" # Fix for Issue 2452 if PY3: try: text = "".join(self.__buffer) except TypeError: text = b"".join(self.__buffer) try: ...
Insert text at the current cursor position or at the end of the command line
def insert_text(self, text, at_end=False, error=False, prompt=False): """ Insert text at the current cursor position or at the end of the command line """ if at_end: # Insert text at the end of the command line self.append_text_to_shell(text, error,...
Drag and Drop - Drop event
def dropEvent(self, event): """Drag and Drop - Drop event""" if (event.mimeData().hasFormat("text/plain")): text = to_text_string(event.mimeData().text()) if self.new_input_line: self.on_new_line() self.insert_text(text, at_end=True) ...
Reimplements ShellBaseWidget method
def setup_context_menu(self): """Reimplements ShellBaseWidget method""" ShellBaseWidget.setup_context_menu(self) self.copy_without_prompts_action = create_action(self, _("Copy without prompts"), icon=ima.icon('copywop...
Reimplements ShellBaseWidget method
def contextMenuEvent(self, event): """Reimplements ShellBaseWidget method""" state = self.has_selected_text() self.copy_without_prompts_action.setEnabled(state) ShellBaseWidget.contextMenuEvent(self, event)
Copy text to clipboard without prompts
def copy_without_prompts(self): """Copy text to clipboard without prompts""" text = self.get_selected_text() lines = text.split(os.linesep) for index, line in enumerate(lines): if line.startswith('>>> ') or line.startswith('... '): lines[index] = line[4:...
Process keypress event
def postprocess_keyevent(self, event): """Process keypress event""" ShellBaseWidget.postprocess_keyevent(self, event) if QToolTip.isVisible(): _event, _text, key, _ctrl, _shift = restore_keyevent(event) self.hide_tooltip_if_necessary(key)
Action for Backspace key
def _key_backspace(self, cursor_position): """Action for Backspace key""" if self.has_selected_text(): self.check_selection() self.remove_selected_text() elif self.current_prompt_pos == cursor_position: # Avoid deleting prompt return ...
Action for TAB key
def _key_tab(self): """Action for TAB key""" if self.is_cursor_on_last_line(): empty_line = not self.get_current_line_to_cursor().strip() if empty_line: self.stdkey_tab() else: self.show_code_completion()
Action for ?
def _key_question(self, text): """Action for '?'""" if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text) # In case calltip and com...
Action for (
def _key_parenleft(self, text): """Action for '('""" self.hide_completion_widget() if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.insert_text(text) self.show_object_i...
Action for.
def _key_period(self, text): """Action for '.'""" self.insert_text(text) if self.codecompletion_auto: # Enable auto-completion only if last token isn't a float last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.s...
Reimplemented slot to handle multiline paste action
def paste(self): """Reimplemented slot to handle multiline paste action""" text = to_text_string(QApplication.clipboard().text()) if len(text.splitlines()) > 1: # Multiline paste if self.new_input_line: self.on_new_line() self.remove_sel...
Display the possible completions
def show_completion_list(self, completions, completion_text=""): """Display the possible completions""" if not completions: return if not isinstance(completions[0], tuple): completions = [(c, '') for c in completions] if len(completions) == 1 and completions...
Display a completion list based on the current line
def show_code_completion(self): """Display a completion list based on the current line""" # Note: unicode conversion is needed only for ExternalShellBase text = to_text_string(self.get_current_line_to_cursor()) last_obj = self.get_last_obj() if not text: return ...
Drop path list
def drop_pathlist(self, pathlist): """Drop path list""" if pathlist: files = ["r'%s'" % path for path in pathlist] if len(files) == 1: text = files[0] else: text = "[" + ", ".join(files) + "]" if self.new_input_line:...
Command to start kernels
def argv(self): """Command to start kernels""" # Python interpreter used to start kernels if CONF.get('main_interpreter', 'default'): pyexec = get_python_executable() else: # Avoid IPython adding the virtualenv on which Spyder is running # to the kerne...
Env vars for kernels
def env(self): """Env vars for kernels""" # Add our PYTHONPATH to the kernel pathlist = CONF.get('main', 'spyder_pythonpath', default=[]) default_interpreter = CONF.get('main_interpreter', 'default') pypath = add_pathlist_to_PYTHONPATH([], pathlist, ipyconsole=True, ...
Setup context menu common actions
def setup_common_actions(self): """Setup context menu common actions""" actions = FilteredDirView.setup_common_actions(self) # Toggle horizontal scrollbar hscrollbar_action = create_action(self, _("Show horizontal scrollbar"), toggled=self...
Toggle horizontal scrollbar
def toggle_hscrollbar(self, checked): """Toggle horizontal scrollbar""" self.parent_widget.sig_option_changed.emit('show_hscrollbar', checked) self.show_hscrollbar = checked self.header().setStretchLastSection(not checked) self.header().setHorizontalScrollMode(QAbstractItemV...
Reimplement Qt method
def dragMoveEvent(self, event): """Reimplement Qt method""" index = self.indexAt(event.pos()) if index: dst = self.get_filename(index) if osp.isdir(dst): event.acceptProposedAction() else: event.ignore() else: ...
Reimplement Qt method
def dropEvent(self, event): """Reimplement Qt method""" event.ignore() action = event.dropAction() if action not in (Qt.MoveAction, Qt.CopyAction): return # QTreeView must not remove the source items even in MoveAction mode: # event.setDropAction(Qt.C...
Delete files
def delete(self, fnames=None): """Delete files""" if fnames is None: fnames = self.get_selected_filenames() multiple = len(fnames) > 1 yes_to_all = None for fname in fnames: if fname == self.proxymodel.path_list[0]: self.sig_delete_...
Set the project directory
def set_project_dir(self, directory): """Set the project directory""" if directory is not None: self.treewidget.set_root_path(osp.dirname(directory)) self.treewidget.set_folder_names([osp.basename(directory)]) self.treewidget.setup_project_view() try: ...
Setup project
def setup_project(self, directory): """Setup project""" self.emptywidget.hide() self.treewidget.show() # Setup the directory shown by the tree self.set_project_dir(directory)
Start Python interpreter
def start_interpreter(self, namespace): """Start Python interpreter""" self.clear() if self.interpreter is not None: self.interpreter.closing() self.interpreter = Interpreter(namespace, self.exitfunc, SysOutput, WidgetPro...
Exit interpreter
def exit_interpreter(self): """Exit interpreter""" self.interpreter.exit_flag = True if self.multithreaded: self.interpreter.stdin_write.write(to_binary_string('\n')) self.interpreter.restore_stds()
Data is available in stdout let s empty the queue and write it!
def stdout_avail(self): """Data is available in stdout, let's empty the queue and write it!""" data = self.interpreter.stdout_write.empty_queue() if data: self.write(data)
Data is available in stderr let s empty the queue and write it!
def stderr_avail(self): """Data is available in stderr, let's empty the queue and write it!""" data = self.interpreter.stderr_write.empty_queue() if data: self.write(data, error=True) self.flush(error=True)
Wait for input ( raw_input support )
def wait_input(self, prompt=''): """Wait for input (raw_input support)""" self.new_prompt(prompt) self.setFocus() self.input_mode = True self.input_loop = QEventLoop() self.input_loop.exec_() self.input_loop = None
End of wait_input mode
def end_input(self, cmd): """End of wait_input mode""" self.input_mode = False self.input_loop.exit() self.interpreter.widget_proxy.end_input(cmd)
Reimplement PythonShellWidget method
def setup_context_menu(self): """Reimplement PythonShellWidget method""" PythonShellWidget.setup_context_menu(self) self.help_action = create_action(self, _("Help..."), icon=ima.icon('DialogHelpButton'), triggered=self.help) sel...
Help on Spyder console
def help(self): """Help on Spyder console""" QMessageBox.about(self, _("Help"), """<b>%s</b> <p><i>%s</i><br> edit foobar.py <p><i>%s</i><br> xedit foobar.py <p><i>%s</i><br> run foobar...
Load file in external Spyder s editor if available This method is used only for embedded consoles ( could also be useful if we ever implement the magic %edit command )
def open_with_external_spyder(self, text): """Load file in external Spyder's editor, if available This method is used only for embedded consoles (could also be useful if we ever implement the magic %edit command)""" match = get_error_match(to_text_string(text)) if match: ...
Edit in an external editor Recommended: SciTE ( e. g. to go to line where an error did occur )
def external_editor(self, filename, goto=-1): """Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)""" editor_path = CONF.get('internal_console', 'external_editor/path') goto_option = CONF.get('internal_console', 'external_editor/gotoline') ...
Reimplement ShellBaseWidget method
def flush(self, error=False, prompt=False): """Reimplement ShellBaseWidget method""" PythonShellWidget.flush(self, error=error, prompt=prompt) if self.interrupted: self.interrupted = False raise KeyboardInterrupt
Reimplement ShellBaseWidget method
def clear_terminal(self): """Reimplement ShellBaseWidget method""" self.clear() self.new_prompt(self.interpreter.p2 if self.interpreter.more else self.interpreter.p1)
on_enter
def on_enter(self, command): """on_enter""" if self.profile: # Simple profiling test t0 = time() for _ in range(10): self.execute_command(command) self.insert_text(u"\n<Δt>=%dms\n" % (1e2*(time()-t0))) self.new_prompt(se...
Flush keyboard event queue
def __flush_eventqueue(self): """Flush keyboard event queue""" while self.eventqueue: past_event = self.eventqueue.pop(0) self.postprocess_keyevent(past_event)
Simulate keyboard interrupt
def keyboard_interrupt(self): """Simulate keyboard interrupt""" if self.multithreaded: self.interpreter.raise_keyboard_interrupt() else: if self.interpreter.more: self.write_error("\nKeyboardInterrupt\n") self.interpreter.more = Fals...
Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands
def execute_lines(self, lines): """ Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands """ for line in lines.splitlines(): stripped_line = line.strip() if stripped_line.startswith('#'): ...
Execute a command cmd: one - line command only with \ n at the end
def execute_command(self, cmd): """ Execute a command cmd: one-line command only, with '\n' at the end """ if self.input_mode: self.end_input(cmd) return if cmd.endswith('\n'): cmd = cmd[:-1] # cls command if ...
Run command in interpreter
def run_command(self, cmd, history=True, new_prompt=True): """Run command in interpreter""" if not cmd: cmd = '' else: if history: self.add_to_history(cmd) if not self.multithreaded: if 'input' not in cmd: self....
Return dir ( object )
def get_dir(self, objtxt): """Return dir(object)""" obj, valid = self._eval(objtxt) if valid: return getobjdir(obj)
Is object callable?
def iscallable(self, objtxt): """Is object callable?""" obj, valid = self._eval(objtxt) if valid: return callable(obj)
Get func/ method argument list
def get_arglist(self, objtxt): """Get func/method argument list""" obj, valid = self._eval(objtxt) if valid: return getargtxt(obj)
Get object documentation dictionary
def get_doc(self, objtxt): """Get object documentation dictionary""" obj, valid = self._eval(objtxt) if valid: return getdoc(obj)
Get object source
def get_source(self, objtxt): """Get object source""" obj, valid = self._eval(objtxt) if valid: return getsource(obj)
Return True if object is defined
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" return self.interpreter.is_defined(objtxt, force_import)
Override Qt method
def paintEvent(self, event): """Override Qt method""" painter = QPainter(self) size = self.size() color = QColor(self.color) color.setAlphaF(.5) painter.setPen(color) for column in self.columns: x = self.editor.fontMetrics().width(column * '9') ...
Set edge line columns values.
def set_columns(self, columns): """Set edge line columns values.""" if isinstance(columns, tuple): self.columns = columns elif is_text_string(columns): self.columns = tuple(int(e) for e in columns.split(',')) self.update()
Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions:. spydata. mat. npy or. h5 which can be imported by the Variable Explorer.
def send_args_to_spyder(args): """ Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions: .spydata, .mat, .npy, or .h5, which can be imported by the Variable Explorer. """ ...
Start Spyder application. If single instance mode is turned on ( default behavior ) and an instance of Spyder is already running this will just parse and send command line options to the application.
def main(): """ Start Spyder application. If single instance mode is turned on (default behavior) and an instance of Spyder is already running, this will just parse and send command line options to the application. """ # Parse command line options if running_under_pytest(): ...
Returns a compiled regex pattern to search for query letters in order.
def get_search_regex(query, ignore_case=True): """Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensit...
Returns a tuple with the enriched text ( if a template is provided ) and a score for the match.
def get_search_score(query, choice, ignore_case=True, apply_regex=True, template='{}'): """Returns a tuple with the enriched text (if a template is provided) and a score for the match. Parameters ---------- query : str String with letters to search in choice (in order o...
Search for query inside choices and return a list of tuples.
def get_search_scores(query, choices, ignore_case=True, template='{}', valid_only=False, sort=False): """Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower sc...
Return True if text is the beginning of the function definition.
def is_start_of_function(text): """Return True if text is the beginning of the function definition.""" if isinstance(text, str) or isinstance(text, unicode): function_prefix = ['def', 'async def'] text = text.lstrip() for prefix in function_prefix: if text.startswith(...