id
stringlengths
30
32
content
stringlengths
139
2.8k
codereview_new_python_data_9103
def is_program_installed(basename): osp.join('/usr', 'local', 'bin'), ] - a = [home, '/opt'] b = ['mambaforge', 'miniforge3', 'miniforge', 'miniconda3', 'anaconda3', 'miniconda', 'anaconda'] else: pyenv = [osp.join(home, '.pyenv', 'pyenv-win', 'bin')] - a = [home, osp.join(home, 'AppData/Local'), - 'C:/', osp.join('C:/', 'ProgramData')] b = ['Mambaforge', 'Miniforge3', 'Miniforge', 'Miniconda3', 'Anaconda3', 'Miniconda', 'Anaconda'] ```suggestion a = [home, osp.join(home, 'opt'), '/opt'] ``` This is missing from the removed code above and I think it's a possibility on Mac. def is_program_installed(basename): osp.join('/usr', 'local', 'bin'), ] + a = [home, osp.join(home, 'opt'), '/opt'] b = ['mambaforge', 'miniforge3', 'miniforge', 'miniconda3', 'anaconda3', 'miniconda', 'anaconda'] else: pyenv = [osp.join(home, '.pyenv', 'pyenv-win', 'bin')] + a = [home, osp.join(home, 'AppData', 'Local'), + 'C:\\', osp.join('C:\\', 'ProgramData')] b = ['Mambaforge', 'Miniforge3', 'Miniforge', 'Miniconda3', 'Anaconda3', 'Miniconda', 'Anaconda']
codereview_new_python_data_9104
def is_program_installed(basename): osp.join('/usr', 'local', 'bin'), ] - a = [home, '/opt'] b = ['mambaforge', 'miniforge3', 'miniforge', 'miniconda3', 'anaconda3', 'miniconda', 'anaconda'] else: pyenv = [osp.join(home, '.pyenv', 'pyenv-win', 'bin')] - a = [home, osp.join(home, 'AppData/Local'), - 'C:/', osp.join('C:/', 'ProgramData')] b = ['Mambaforge', 'Miniforge3', 'Miniforge', 'Miniconda3', 'Anaconda3', 'Miniconda', 'Anaconda'] This would give a weird mix of `/` and `\\` for these paths (due to the usage of `osp.join`). Why not keep using `\\` as before? def is_program_installed(basename): osp.join('/usr', 'local', 'bin'), ] + a = [home, osp.join(home, 'opt'), '/opt'] b = ['mambaforge', 'miniforge3', 'miniforge', 'miniconda3', 'anaconda3', 'miniconda', 'anaconda'] else: pyenv = [osp.join(home, '.pyenv', 'pyenv-win', 'bin')] + a = [home, osp.join(home, 'AppData', 'Local'), + 'C:\\', osp.join('C:\\', 'ProgramData')] b = ['Mambaforge', 'Miniforge3', 'Miniforge', 'Miniconda3', 'Anaconda3', 'Miniconda', 'Anaconda']
codereview_new_python_data_9105
def replace_find_all(self): else: pattern = re.escape(search_text) replace_text = replace_text.replace('\\', r'\\') - if word: # match whole words only pattern = r'\b{pattern}\b'.format(pattern=pattern) # Check regexp before proceeding ```suggestion # Match whole words only if word: pattern = r'\b{pattern}\b'.format(pattern=pattern) ``` def replace_find_all(self): else: pattern = re.escape(search_text) replace_text = replace_text.replace('\\', r'\\') + + # Match whole words only + if word: pattern = r'\b{pattern}\b'.format(pattern=pattern) # Check regexp before proceeding
codereview_new_python_data_9106
def test_plots_scroll(main_window, qtbot): " plt.plot([1, 2, 3, 4], '.')\n" " plt.show()\n" " time.sleep(.1)") - qtbot.waitUntil(lambda: sb._first_thumbnail_shown, timeout=SHELL_TIMEOUT) sb.set_current_index(5) scrollbar.setValue(scrollbar.minimum()) ```suggestion qtbot.waitUntil(lambda: sb._first_thumbnail_shown, timeout=SHELL_TIMEOUT) ``` def test_plots_scroll(main_window, qtbot): " plt.plot([1, 2, 3, 4], '.')\n" " plt.show()\n" " time.sleep(.1)") + qtbot.waitUntil(lambda: sb._first_thumbnail_shown, + timeout=SHELL_TIMEOUT) sb.set_current_index(5) scrollbar.setValue(scrollbar.minimum())
codereview_new_python_data_9107
def get_conda_activation_script(quote=False): exe = get_spyder_umamba_path() or find_conda() if osp.basename(exe) in ('micromamba.exe', 'conda.exe'): - # For stadalone conda, use the executable script_path = exe else: # Conda activation script is relative to executable Should this be `_conda.exe` instead of `conda.exe`? def get_conda_activation_script(quote=False): exe = get_spyder_umamba_path() or find_conda() if osp.basename(exe) in ('micromamba.exe', 'conda.exe'): + # For standalone conda, use the executable script_path = exe else: # Conda activation script is relative to executable
codereview_new_python_data_9108
def translate_gettext(x): #============================================================================== def running_in_mac_app(pyexec=sys.executable): """ - Check if Spyder is running as a macOS bundle app. - Checks for SPYDER_APP environment variable to determine this. - If python executable is provided, checks if it is the same as the macOS bundle app environment executable. """ # Spyder is macOS app mac_app = os.environ.get('SPYDER_APP') is not None - if mac_app and pyexec == sys.executable: # executable is macOS app return True else: ```suggestion Check if Spyder is running as a macOS bundle app by looking for the `SPYDER_APP` environment variable. ``` def translate_gettext(x): #============================================================================== def running_in_mac_app(pyexec=sys.executable): """ + Check if Spyder is running as a macOS bundle app by looking for the + `SPYDER_APP` environment variable. + If a python executable is provided, checks if it is the same as the macOS bundle app environment executable. """ # Spyder is macOS app mac_app = os.environ.get('SPYDER_APP') is not None + if sys.platform == 'darwin' and mac_app and pyexec == sys.executable: # executable is macOS app return True else:
codereview_new_python_data_9109
def translate_gettext(x): #============================================================================== def running_in_mac_app(pyexec=sys.executable): """ - Check if Spyder is running as a macOS bundle app. - Checks for SPYDER_APP environment variable to determine this. - If python executable is provided, checks if it is the same as the macOS bundle app environment executable. """ # Spyder is macOS app mac_app = os.environ.get('SPYDER_APP') is not None - if mac_app and pyexec == sys.executable: # executable is macOS app return True else: ```suggestion If a python executable is provided, checks if it is the same as the macOS bundle app environment executable. ``` def translate_gettext(x): #============================================================================== def running_in_mac_app(pyexec=sys.executable): """ + Check if Spyder is running as a macOS bundle app by looking for the + `SPYDER_APP` environment variable. + If a python executable is provided, checks if it is the same as the macOS bundle app environment executable. """ # Spyder is macOS app mac_app = os.environ.get('SPYDER_APP') is not None + if sys.platform == 'darwin' and mac_app and pyexec == sys.executable: # executable is macOS app return True else:
codereview_new_python_data_9110
def translate_gettext(x): #============================================================================== def running_in_mac_app(pyexec=sys.executable): """ - Check if Spyder is running as a macOS bundle app. - Checks for SPYDER_APP environment variable to determine this. - If python executable is provided, checks if it is the same as the macOS bundle app environment executable. """ # Spyder is macOS app mac_app = os.environ.get('SPYDER_APP') is not None - if mac_app and pyexec == sys.executable: # executable is macOS app return True else: ```suggestion if sys.platform == 'darwin' and mac_app and pyexec == sys.executable: ``` This check can easily be passed in other platforms just by setting `SPYDER_APP`. def translate_gettext(x): #============================================================================== def running_in_mac_app(pyexec=sys.executable): """ + Check if Spyder is running as a macOS bundle app by looking for the + `SPYDER_APP` environment variable. + If a python executable is provided, checks if it is the same as the macOS bundle app environment executable. """ # Spyder is macOS app mac_app = os.environ.get('SPYDER_APP') is not None + if sys.platform == 'darwin' and mac_app and pyexec == sys.executable: # executable is macOS app return True else:
codereview_new_python_data_9111
def get_conda_activation_script(quote=False): exe = get_spyder_umamba_path() or find_conda() if osp.basename(exe) in ('micromamba.exe', 'conda.exe'): - # For stadalone conda, use the executable script_path = exe else: # Conda activation script is relative to executable ```suggestion # For standalone conda, use the executable ``` def get_conda_activation_script(quote=False): exe = get_spyder_umamba_path() or find_conda() if osp.basename(exe) in ('micromamba.exe', 'conda.exe'): + # For standalone conda, use the executable script_path = exe else: # Conda activation script is relative to executable
codereview_new_python_data_9112
def get_user_environment_variables(): try: k, v = kv.split('=', 1) env_var[k] = v - except: pass return env_var ```suggestion except Exception: ``` It's usually not a good idea to leave bare excepts. def get_user_environment_variables(): try: k, v = kv.split('=', 1) env_var[k] = v + except Exception: pass return env_var
codereview_new_python_data_9113
from qtpy.QtCore import Qt from qtpy.QtTest import QTest from qtpy.QtWidgets import QApplication, QFileDialog, QLineEdit, QTabBar -from qtpy import QtWebEngineWidgets import psutil import pytest ```suggestion # This is required to run our tests in VSCode or Spyder-unittest from qtpy import QtWebEngineWidgets # noqa ``` Add a clarifying comment and `# noqa` so we don't remove this line in the future if it's reported by linters as unnecessary. from qtpy.QtCore import Qt from qtpy.QtTest import QTest from qtpy.QtWidgets import QApplication, QFileDialog, QLineEdit, QTabBar +# This is required to run our tests in VSCode or Spyder-unittest +from qtpy import QtWebEngineWidgets # noqa import psutil import pytest
codereview_new_python_data_9114
"""Tests for gotoline.py""" # Third party imports -from qtpy.QtWidgets import QDialogButtonBox, QPushButton, QTableWidget, QLineEdit # Local imports from spyder.plugins.editor.widgets.gotoline import GoToLineDialog def test_gotolinedialog_has_cancel_button(codeeditor, qtbot, tmpdir): """ Test that GoToLineDialog has a Cancel button. Missing blank line here: ```suggestion ``` """Tests for gotoline.py""" # Third party imports +from qtpy.QtWidgets import QDialogButtonBox, QLineEdit # Local imports from spyder.plugins.editor.widgets.gotoline import GoToLineDialog + def test_gotolinedialog_has_cancel_button(codeeditor, qtbot, tmpdir): """ Test that GoToLineDialog has a Cancel button.
codereview_new_python_data_9115
def test_dedicated_consoles(main_window, qtbot): text = control.toPlainText() assert ('runfile' in text) and not ('Python' in text or 'IPython' in text) - # --- Clean retained after re-execution --- with qtbot.waitSignal(shell.executed): shell.execute('zz = -1') Maybe this comment could be clearer writting something like `Check namespace retention after re-execution`? def test_dedicated_consoles(main_window, qtbot): text = control.toPlainText() assert ('runfile' in text) and not ('Python' in text or 'IPython' in text) + # --- Check namespace retention after re-execution --- with qtbot.waitSignal(shell.executed): shell.execute('zz = -1')
codereview_new_python_data_9116
def start_installation(self, latest_release): def set_download_progress(self, current_value, total): percentage_progress = 0 if total > 0: - percentage_progress = int(current_value/total*100) self.custom_widget.setText(f"{percentage_progress} %") def set_status_pending(self, latest_release): ```suggestion percentage_progress = int((current_value/total) * 100) ``` def start_installation(self, latest_release): def set_download_progress(self, current_value, total): percentage_progress = 0 if total > 0: + percentage_progress = int((current_value/total) * 100) self.custom_widget.setText(f"{percentage_progress} %") def set_status_pending(self, latest_release):
codereview_new_python_data_9117
def start_installation(self, latest_release): def set_download_progress(self, current_value, total): percentage_progress = 0 if total > 0: - percentage_progress = int((current_value/total) * 100) - self.custom_widget.setText(f"{percentage_progress} %") def set_status_pending(self, latest_release): self.set_value(PENDING) ```suggestion percentage_progress = round((current_value/total) * 100) ``` Perhaps slightly more idiomatic (and perhaps a tad more representative, since it rounds rather than truncates) def start_installation(self, latest_release): def set_download_progress(self, current_value, total): percentage_progress = 0 if total > 0: + percentage_progress = round((current_value/total) * 100) + self.custom_widget.setText(f"{percentage_progress}%") def set_status_pending(self, latest_release): self.set_value(PENDING)
codereview_new_python_data_9118
if boot_branch_file.exists(): prev_branch = boot_branch_file.read_text() - res, err = run_program( find_git(), ['merge-base', '--fork-point', 'master'] ).communicate() - branch = "master" if res else "not master" boot_branch_file.write_text(branch) logger.info("Previous root branch: %s; current root branch: %s", prev_branch, branch) if branch != prev_branch: logger.info("Detected root branch change to/from master. " - "Will reinstall spyder in editable mode.") REPOS["spyder"]["editable"] = False for name in REPOS.keys(): Does `res` stands for `result` and `err` for `error`? If that's the case, please use those variable names to be more explicit. if boot_branch_file.exists(): prev_branch = boot_branch_file.read_text() + result, error = run_program( find_git(), ['merge-base', '--fork-point', 'master'] ).communicate() + branch = "master" if result else "not master" boot_branch_file.write_text(branch) logger.info("Previous root branch: %s; current root branch: %s", prev_branch, branch) if branch != prev_branch: logger.info("Detected root branch change to/from master. " + "Will reinstall Spyder in editable mode.") REPOS["spyder"]["editable"] = False for name in REPOS.keys():
codereview_new_python_data_9119
if boot_branch_file.exists(): prev_branch = boot_branch_file.read_text() - res, err = run_program( find_git(), ['merge-base', '--fork-point', 'master'] ).communicate() - branch = "master" if res else "not master" boot_branch_file.write_text(branch) logger.info("Previous root branch: %s; current root branch: %s", prev_branch, branch) if branch != prev_branch: logger.info("Detected root branch change to/from master. " - "Will reinstall spyder in editable mode.") REPOS["spyder"]["editable"] = False for name in REPOS.keys(): ```suggestion "Will reinstall Spyder in editable mode.") ``` if boot_branch_file.exists(): prev_branch = boot_branch_file.read_text() + result, error = run_program( find_git(), ['merge-base', '--fork-point', 'master'] ).communicate() + branch = "master" if result else "not master" boot_branch_file.write_text(branch) logger.info("Previous root branch: %s; current root branch: %s", prev_branch, branch) if branch != prev_branch: logger.info("Detected root branch change to/from master. " + "Will reinstall Spyder in editable mode.") REPOS["spyder"]["editable"] = False for name in REPOS.keys():
codereview_new_python_data_9120
class UpdateInstallerDialog(QDialog): current_value: int Size of the data downloaded until now. total: int - Total size file expected to be downloaded. """ sig_installation_status = Signal(str, str) ```suggestion Total size of the file expected to be downloaded. ``` class UpdateInstallerDialog(QDialog): current_value: int Size of the data downloaded until now. total: int + Total size of the file expected to be downloaded. """ sig_installation_status = Signal(str, str)
codereview_new_python_data_9121
class WorkerDownloadInstaller(QObject): current_value: int Size of the data downloaded until now. total: int - Total size file expected to be downloaded. """ def __init__(self, parent, latest_release_version): ```suggestion Total size of the file expected to be downloaded. ``` class WorkerDownloadInstaller(QObject): current_value: int Size of the data downloaded until now. total: int + Total size of the file expected to be downloaded. """ def __init__(self, parent, latest_release_version):
codereview_new_python_data_9122
def on_initialize(self): self.create_action( BreakpointsActions.ListBreakpoints, _("List breakpoints"), - triggered=self.switch_to_plugin, icon=self.get_icon(), ) Instead of calling this directly, please emit `sig_switch_to_plugin_requested`. def on_initialize(self): self.create_action( BreakpointsActions.ListBreakpoints, _("List breakpoints"), + triggered=self.sig_switch_to_plugin_requested, icon=self.get_icon(), )
codereview_new_python_data_9123
def set_filename(self, filename): self.filecombo.selected() - @Slot() def start_code_analysis(self, filename=None): """ Perform code analysis for given `filename`. Is this `Slot` really necessary? It seems we only need it in the `start_code_analysis` method of the plugin, not here. def set_filename(self, filename): self.filecombo.selected() def start_code_analysis(self, filename=None): """ Perform code analysis for given `filename`.
codereview_new_python_data_9124
def pdb_execute(self, line, hidden=False, echo_stack_entry=True, # --- To Sort -------------------------------------------------- def stop_debugging(self): """Stop debugging.""" - if (self.spyder_kernel_ready and not self.is_waiting_pdb_input()): self.interrupt_kernel() self.pdb_execute_command("exit") ```suggestion if self.spyder_kernel_ready and not self.is_waiting_pdb_input(): ``` def pdb_execute(self, line, hidden=False, echo_stack_entry=True, # --- To Sort -------------------------------------------------- def stop_debugging(self): """Stop debugging.""" + if self.spyder_kernel_ready and not self.is_waiting_pdb_input(): self.interrupt_kernel() self.pdb_execute_command("exit")
codereview_new_python_data_9125
def _when_kernel_is_ready(self): """ Configuration after the prompt is shown. - Note: - This is not called on restart. For kernel setup, - use ShellWidget.handle_kernel_is_ready """ if self.kernel_handler.connection_state not in [ KernelConnectionState.SpyderKernelReady, ```suggestion Notes ----- This is not called on restart. For kernel setup you need to use ShellWidget.handle_kernel_is_ready. ``` def _when_kernel_is_ready(self): """ Configuration after the prompt is shown. + Notes + ----- + This is not called on restart. For kernel setup you need to use + ShellWidget.handle_kernel_is_ready. """ if self.kernel_handler.connection_state not in [ KernelConnectionState.SpyderKernelReady,
codereview_new_python_data_9126
def handle_kernel_is_ready(self): return def handle_kernel_connection_error(self): - """An error occured.""" if self.kernel_handler.connection_state == KernelConnectionState.Error: # A wrong version is connected self.append_html_message( ```suggestion """An error occurred when connecting to the kernel.""" ``` def handle_kernel_is_ready(self): return def handle_kernel_connection_error(self): + """An error occurred when connecting to the kernel.""" if self.kernel_handler.connection_state == KernelConnectionState.Error: # A wrong version is connected self.append_html_message(
codereview_new_python_data_9127
def save(self, index=None, force=False, save_new_files=True): self.set_os_eol_chars(osname=osname) try: - if (self.format_on_save and - finfo.editor.formatting_enabled and - finfo.editor.is_python()): # Wait for document autoformat in case it is a Python file # and then save. # Just trigger the autoformat for Python files. ```suggestion if ( self.format_on_save and finfo.editor.formatting_enabled and finfo.editor.is_python() ): ``` def save(self, index=None, force=False, save_new_files=True): self.set_os_eol_chars(osname=osname) try: + if ( + self.format_on_save + and finfo.editor.formatting_enabled + and finfo.editor.is_python() + ): # Wait for document autoformat in case it is a Python file # and then save. # Just trigger the autoformat for Python files.
codereview_new_python_data_9128
def run_selection(self, prefix=None): """ if prefix is None: prefix = '' text = self.get_current_editor().get_selection_as_executable_code() if text: self.exec_in_extconsole.emit( prefix + text.rstrip(), self.focus_to_editor) return editor = self.get_current_editor() line = editor.get_current_line() text = line.lstrip() ```suggestion prefix = '' ``` def run_selection(self, prefix=None): """ if prefix is None: prefix = '' + text = self.get_current_editor().get_selection_as_executable_code() if text: self.exec_in_extconsole.emit( prefix + text.rstrip(), self.focus_to_editor) return + editor = self.get_current_editor() line = editor.get_current_line() text = line.lstrip()
codereview_new_python_data_9129
def run_selection(self, prefix=None): """ if prefix is None: prefix = '' text = self.get_current_editor().get_selection_as_executable_code() if text: self.exec_in_extconsole.emit( prefix + text.rstrip(), self.focus_to_editor) return editor = self.get_current_editor() line = editor.get_current_line() text = line.lstrip() ```suggestion editor = self.get_current_editor() ``` def run_selection(self, prefix=None): """ if prefix is None: prefix = '' + text = self.get_current_editor().get_selection_as_executable_code() if text: self.exec_in_extconsole.emit( prefix + text.rstrip(), self.focus_to_editor) return + editor = self.get_current_editor() line = editor.get_current_line() text = line.lstrip()
codereview_new_python_data_9130
def setup(self): goto_cursor_action = self.create_action( DebuggerWidgetActions.GotoCursor, - text=_("Show in editor"), icon=self.create_icon('fromcursor'), triggered=self.goto_current_step, register_shortcut=True ```suggestion text=_("Show in the editor the file and line where the debugger " "is placed"), ``` Make this a bit more verbose so that it's easier to understand what it does. def setup(self): goto_cursor_action = self.create_action( DebuggerWidgetActions.GotoCursor, + text=_("Show in the editor the file and line where the debugger " + "is placed"), icon=self.create_icon('fromcursor'), triggered=self.goto_current_step, register_shortcut=True
codereview_new_python_data_9131
def update_pdb_state(self, state, filename, line_number): ): self.debugger_panel.start_clean() self.debugger_panel.set_current_line_arrow(line_number) - return self.debugger_panel.stop_clean() def set_filename(self, filename): ```suggestion return ``` Sorry, this was my mistake from a previous review. def update_pdb_state(self, state, filename, line_number): ): self.debugger_panel.start_clean() self.debugger_panel.set_current_line_arrow(line_number) return + self.debugger_panel.stop_clean() def set_filename(self, filename):
codereview_new_python_data_9132
def test_project_path(main_window, tmpdir, qtbot): projects = main_window.projects # Create a project - path = to_text_string(tmpdir.mkdir('project_path')) assert path not in projects.get_conf('spyder_pythonpath', section='main') ```suggestion path = str(tmpdir.mkdir('project_path')) ``` `to_text_string` was a `str` version compatible with Python 2, but it's not necessary anymore. def test_project_path(main_window, tmpdir, qtbot): projects = main_window.projects # Create a project + path = str(tmpdir.mkdir('project_path')) assert path not in projects.get_conf('spyder_pythonpath', section='main')
codereview_new_python_data_9133
class ShellWidget(NamepaceBrowserWidget, HelpWidget, DebuggingWidget, # For DebuggingWidget sig_pdb_step = Signal(str, int) """Called when pdb reaches a new line""" sig_pdb_stack = Signal(object, int) """Called when the pdb stack changed""" sig_pdb_state_changed = Signal(bool, dict) """Called every time a pdb interaction happens""" sig_pdb_prompt_ready = Signal() """Called when pdb request new input""" ```suggestion sig_pdb_step = Signal(str, int) """Called when pdb reaches a new line""" sig_pdb_stack = Signal(object, int) """Called when the pdb stack changed""" sig_pdb_state_changed = Signal(bool, dict) """Called every time a pdb interaction happens""" sig_pdb_prompt_ready = Signal() """Called when pdb request new input""" ``` class ShellWidget(NamepaceBrowserWidget, HelpWidget, DebuggingWidget, # For DebuggingWidget sig_pdb_step = Signal(str, int) """Called when pdb reaches a new line""" + sig_pdb_stack = Signal(object, int) """Called when the pdb stack changed""" + sig_pdb_state_changed = Signal(bool, dict) """Called every time a pdb interaction happens""" + sig_pdb_prompt_ready = Signal() """Called when pdb request new input"""
codereview_new_python_data_9134
def setup_page(self): _("Process execute events while debugging"), 'pdb_execute_events', tip=_("This option lets you decide if the debugger should " "process the 'execute events' after each prompt, such as " - "matplotlib 'show' command.")) debug_layout.addWidget(execute_events_box) exclamation_mark_box = newcb( ```suggestion "matplotlib <tt>show</tt> command.")) ``` def setup_page(self): _("Process execute events while debugging"), 'pdb_execute_events', tip=_("This option lets you decide if the debugger should " "process the 'execute events' after each prompt, such as " + "matplotlib <tt>show</tt> command.")) debug_layout.addWidget(execute_events_box) exclamation_mark_box = newcb(
codereview_new_python_data_9135
def run_script(self, filename, wdir, args='', focus_to_editor: bool, optional Leave focus in the editor after execution. method : str or None - method to run the file. must accept the same arguments as runfile. force_wdir: bool - the working directory is ignored on remote kernel except if force_wdir is True Returns ```suggestion Method to run the file. It must accept the same arguments as `runfile`. ``` def run_script(self, filename, wdir, args='', focus_to_editor: bool, optional Leave focus in the editor after execution. method : str or None + Method to run the file. It must accept the same arguments as + `runfile`. force_wdir: bool + The working directory is ignored on remote kernels except if force_wdir is True Returns
codereview_new_python_data_9136
def run_script(self, filename, wdir, args='', focus_to_editor: bool, optional Leave focus in the editor after execution. method : str or None - method to run the file. must accept the same arguments as runfile. force_wdir: bool - the working directory is ignored on remote kernel except if force_wdir is True Returns ```suggestion The working directory is ignored on remote kernels except if ``` def run_script(self, filename, wdir, args='', focus_to_editor: bool, optional Leave focus in the editor after execution. method : str or None + Method to run the file. It must accept the same arguments as + `runfile`. force_wdir: bool + The working directory is ignored on remote kernels except if force_wdir is True Returns
codereview_new_python_data_9137
def pre_visible_setup(self): pass # Register custom layouts - for plugin_name in PLUGIN_REGISTRY.external_plugins: - plugin_instance = PLUGIN_REGISTRY.get_plugin(plugin_name) - if hasattr(plugin_instance, 'CUSTOM_LAYOUTS'): - if isinstance(plugin_instance.CUSTOM_LAYOUTS, list): - for custom_layout in plugin_instance.CUSTOM_LAYOUTS: - self.layouts.register_layout( - self.layouts, custom_layout) - else: - logger.info( - 'Unable to load custom layouts for {}. ' - 'Expecting a list of layout classes but got {}' - .format(plugin_name, plugin_instance.CUSTOM_LAYOUTS) - ) # Needed to ensure dockwidgets/panes layout size distribution # when a layout state is already present. Shouldn't this be `plugin_instance` instead of `self.layouts`? Also, maybe moving this code to register custom layouts inside the Layout plugin and instead here call something like `self.layouts.register_custom_layouts(PLUGIN_REGISTRY.external_plugins)` could be worthy? def pre_visible_setup(self): pass # Register custom layouts + if self.layouts is not None: + self.layouts.register_custom_layouts() # Needed to ensure dockwidgets/panes layout size distribution # when a layout state is already present.
codereview_new_python_data_9138
def get_interpreter_info(path): try: out, __ = run_program(path, ['-V']).communicate() out = out.decode() - # Needed to prevent showing unexpected output. # See spyder-ide/spyder#19000 if not re.search(r'^Python \d+\.\d+\.\d+$', out): out = '' ```suggestion # This is necessary to prevent showing unexpected output. ``` def get_interpreter_info(path): try: out, __ = run_program(path, ['-V']).communicate() out = out.decode() + + # This is necessary to prevent showing unexpected output. # See spyder-ide/spyder#19000 if not re.search(r'^Python \d+\.\d+\.\d+$', out): out = ''
codereview_new_python_data_9139
def run_terminal_thread(): raise NotImplementedError -def check_version_range(module_version, version): """ - Check version string of a module against a required version. """ if ';' in version: versions = version.split(';') ```suggestion Check if a module's version lies in `version_range`. ``` def run_terminal_thread(): raise NotImplementedError +def check_version_range(module_version, version_range): """ + Check if a module's version lies in `version_range`. """ if ';' in version: versions = version.split(';')
codereview_new_python_data_9140
def create_client_for_kernel(self, connection_file, hostname, sshkey, # Assign kernel manager and client to shellwidget kernel_client.start_channels() shellwidget = client.shellwidget if not known_spyder_kernel: shellwidget.sig_is_spykernel.connect( self.connect_external_spyder_kernel) ```suggestion if not known_spyder_kernel: ``` For clarity. def create_client_for_kernel(self, connection_file, hostname, sshkey, # Assign kernel manager and client to shellwidget kernel_client.start_channels() shellwidget = client.shellwidget + if not known_spyder_kernel: shellwidget.sig_is_spykernel.connect( self.connect_external_spyder_kernel)
codereview_new_python_data_9141
IPython Console plugin based on QtConsole """ # Required version of Spyder-kernels SPYDER_KERNELS_MIN_VERSION = '2.3.0' SPYDER_KERNELS_MAX_VERSION = '2.4.0' ```suggestion # Required version of Spyder-kernels ``` IPython Console plugin based on QtConsole """ + # Required version of Spyder-kernels SPYDER_KERNELS_MIN_VERSION = '2.3.0' SPYDER_KERNELS_MAX_VERSION = '2.4.0'
codereview_new_python_data_9142
import os from qtpy.QtWidgets import QApplication, QMessageBox -if not os.name == 'nt': - import pexpect from spyder.config.base import _ ```suggestion import pexpect ``` Now we really on `pexpect` on all operating systems. import os from qtpy.QtWidgets import QApplication, QMessageBox +import pexpect from spyder.config.base import _
codereview_new_python_data_9143
def unmaximize(self): """Unmaximize the currently maximized plugin, if not self.""" if self.main: layouts = self.get_plugin(Plugins.Layout) - last_plugin = layouts.get_last_plugin() - is_maximized = False - - if last_plugin is not None: - try: - # New API - is_maximized = ( - last_plugin.get_widget().get_maximized_state() - ) - except AttributeError: - # Old API - is_maximized = last_plugin._ismaximized - - if ( - last_plugin is not None - and is_maximized - and last_plugin is not self - ): - layouts.unmaximize_dockwidget() def build_opener(self, project): """Build function opening passed project""" Should this logic be in the `Layout` plugin? Maybe a method with a signature like `unmaximize_other_dockwidget(self, plugin_instance)` or maybe could be worthy to modify the current `unmaximize_dockwidget` method to recieve a kwarg, something like `check_plugin_instance=None`. With that there the kwarg could be used to pass `self` and then this will become `layouts.unmaximize_dockwidget(check_plugin_instance=self)` def unmaximize(self): """Unmaximize the currently maximized plugin, if not self.""" if self.main: layouts = self.get_plugin(Plugins.Layout) + layouts.unmaximize_other_dockwidget(plugin_instance=self) def build_opener(self, project): """Build function opening passed project"""
codereview_new_python_data_9144
def _unmaximize_plugin(self): Notes ----- - We assume that users want to check output in the IPython console after after running or debugging code. And for that we need to unmaximize any plugin that is currently maximized. """ ```suggestion We assume that users want to check output in the IPython console after running or debugging code. And for that we need to unmaximize any ``` def _unmaximize_plugin(self): Notes ----- + We assume that users want to check output in the IPython console after running or debugging code. And for that we need to unmaximize any plugin that is currently maximized. """
codereview_new_python_data_9145
def _change_client_conf(self, client, client_conf_func, value): sw.set_pdb_ignore_lib, sw.set_pdb_execute_events, sw.set_pdb_use_exclamation_mark, - sw.set_pdb_stop_first_line, - ]: # Execute immediately if this is pdb conf client_conf_func(value) else: ```suggestion sw.set_pdb_stop_first_line]: ``` def _change_client_conf(self, client, client_conf_func, value): sw.set_pdb_ignore_lib, sw.set_pdb_execute_events, sw.set_pdb_use_exclamation_mark, + sw.set_pdb_stop_first_line]: # Execute immediately if this is pdb conf client_conf_func(value) else:
codereview_new_python_data_9146
get_home_dir, get_conf_path, get_module_path, running_in_ci) from spyder.config.manager import CONF from spyder.dependencies import DEPENDENCIES -from spyder.plugins.completion.api import DiagnosticSeverity from spyder.plugins.help.widgets import ObjectComboBox from spyder.plugins.help.tests.test_plugin import check_text from spyder.plugins.ipythonconsole.utils.kernelspec import SpyderKernelSpec This import seems unnecessary. If that's the case, please remove it. get_home_dir, get_conf_path, get_module_path, running_in_ci) from spyder.config.manager import CONF from spyder.dependencies import DEPENDENCIES from spyder.plugins.help.widgets import ObjectComboBox from spyder.plugins.help.tests.test_plugin import check_text from spyder.plugins.ipythonconsole.utils.kernelspec import SpyderKernelSpec
codereview_new_python_data_9147
def _update(self): editor = self.editor if editor is None: return try: font = editor.font() ```suggestion return ``` For clarity. def _update(self): editor = self.editor if editor is None: return + try: font = editor.font()
codereview_new_python_data_9148
def get_passed_tests(): with open('pytest_log.txt') as f: logfile = f.readlines() - # All lines that start with 'spyder' are tests. The rest are - # informative messages. test_re = re.compile(r'(spyder.*) (SKIPPED|PASSED|XFAIL) ') tests = [] for line in logfile: ```suggestion # Detect all tests that passed before. ``` def get_passed_tests(): with open('pytest_log.txt') as f: logfile = f.readlines() + # Detect all tests that passed before. test_re = re.compile(r'(spyder.*) (SKIPPED|PASSED|XFAIL) ') tests = [] for line in logfile:
codereview_new_python_data_9149
def block_safe(block): """ Check if the block is safe to work with. - A BlockUserData must have been set on the block while it was known safe. If an editor is cleared by editor.clear() or editor.set_text() for example, - all the old blocks will continue to report block.isValid() == True - but will raise a Segmentation Fault on almost all methods. - One way to check is that the userData is reset to None or - QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. """ return block.isValid() and isinstance(block.userData(), BlockUserData) ```suggestion A BlockUserData must have been set on the block while it was known to be safe. ``` def block_safe(block): """ Check if the block is safe to work with. + A BlockUserData must have been set on the block while it was known to be + safe. If an editor is cleared by editor.clear() or editor.set_text() for example, + all old blocks will continue to report block.isValid() == True, but will + raise a segmentation fault on almost all methods. + One way to check if a block is valid is that the userData is reset to None + or QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. """ return block.isValid() and isinstance(block.userData(), BlockUserData)
codereview_new_python_data_9150
def block_safe(block): """ Check if the block is safe to work with. - A BlockUserData must have been set on the block while it was known safe. If an editor is cleared by editor.clear() or editor.set_text() for example, - all the old blocks will continue to report block.isValid() == True - but will raise a Segmentation Fault on almost all methods. - One way to check is that the userData is reset to None or - QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. """ return block.isValid() and isinstance(block.userData(), BlockUserData) ```suggestion all old blocks will continue to report block.isValid() == True, but will raise a segmentation fault on almost all methods. ``` def block_safe(block): """ Check if the block is safe to work with. + A BlockUserData must have been set on the block while it was known to be + safe. If an editor is cleared by editor.clear() or editor.set_text() for example, + all old blocks will continue to report block.isValid() == True, but will + raise a segmentation fault on almost all methods. + One way to check if a block is valid is that the userData is reset to None + or QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. """ return block.isValid() and isinstance(block.userData(), BlockUserData)
codereview_new_python_data_9151
def block_safe(block): """ Check if the block is safe to work with. - A BlockUserData must have been set on the block while it was known safe. If an editor is cleared by editor.clear() or editor.set_text() for example, - all the old blocks will continue to report block.isValid() == True - but will raise a Segmentation Fault on almost all methods. - One way to check is that the userData is reset to None or - QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. """ return block.isValid() and isinstance(block.userData(), BlockUserData) ```suggestion One way to check if a block is valid is that the userData is reset to None or QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. ``` def block_safe(block): """ Check if the block is safe to work with. + A BlockUserData must have been set on the block while it was known to be + safe. If an editor is cleared by editor.clear() or editor.set_text() for example, + all old blocks will continue to report block.isValid() == True, but will + raise a segmentation fault on almost all methods. + One way to check if a block is valid is that the userData is reset to None + or QTextBlockUserData. So if a block is known to have setUserData to BlockUserData, this fact can be used to check the block. """ return block.isValid() and isinstance(block.userData(), BlockUserData)
codereview_new_python_data_9152
def set_value(self, value): elif value == PENDING: self.tooltip = value else: - value = versions['spyder'] self.tooltip = self.BASE_TOOLTIP self.setVisible(True) self.update_tooltip() Following the changes to the install `NO_STATUS`, then this line could be removed and instead call the `set_no_status` when needed: ```suggestion ``` def set_value(self, value): elif value == PENDING: self.tooltip = value else: self.tooltip = self.BASE_TOOLTIP self.setVisible(True) self.update_tooltip()
codereview_new_python_data_9153
def continue_install(self): reply.setWindowTitle("Spyder") reply.setAttribute(Qt.WA_ShowWithoutActivating) reply.setStandardButtons(QMessageBox.Yes | QMessageBox.No) - reply.buttonClicked.connect( - lambda button: - self.start_installation_update() - if button.text() in ('&Yes') - else self._change_update_installation_status( - status=PENDING)) reply.show() def finished_installation(self, status): """Handle finished installation.""" A similar approach as the one described at `container.py` could be used here (changing the usage of `show` for `exec_` and `result`) def continue_install(self): reply.setWindowTitle("Spyder") reply.setAttribute(Qt.WA_ShowWithoutActivating) reply.setStandardButtons(QMessageBox.Yes | QMessageBox.No) reply.show() + reply.exec_() + if reply.result() == QMessageBox.Yes: + self.start_installation_update() + else: + self._change_update_installation_status(status=PENDING) def finished_installation(self, status): """Handle finished installation."""
codereview_new_python_data_9154
def on_statusbar_available(self): @on_plugin_teardown(plugin=Plugins.StatusBar) def on_statusbar_teardown(self): - # Add status widget statusbar = self.get_plugin(Plugins.StatusBar) statusbar.remove_status_widget(self.application_update_status.ID) ```suggestion # Remove status widget ``` def on_statusbar_available(self): @on_plugin_teardown(plugin=Plugins.StatusBar) def on_statusbar_teardown(self): + # Remove status widget statusbar = self.get_plugin(Plugins.StatusBar) statusbar.remove_status_widget(self.application_update_status.ID)
codereview_new_python_data_9155
# Licensed under the terms of the MIT License # (see spyder/__init__.py for details) -"""Widgets for the application plugin.""" ```suggestion """Widgets for the Application plugin.""" ``` # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) +"""Widgets for the Application plugin."""
codereview_new_python_data_9156
def cancel_install(self): QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: self.cancelled = True - self.cancell_thread_install_update() self.setup() self.accept() return True ```suggestion self.cancel_thread_install_update() ``` Sorry, I forgot to suggest this change in my previous review. def cancel_install(self): QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: self.cancelled = True + self.cancel_thread_install_update() self.setup() self.accept() return True
codereview_new_python_data_9157
def set_value(self, value): self.tooltip = self.BASE_TOOLTIP self.setVisible(True) self.update_tooltip() - value = "Spyder: {0}".format(value) super().set_value(value) def get_tooltip(self): Lets add here a debug log entry and change to use f-string to format. For the debug log, you can use the defined `logger` calling something like: `logger.debug(f"Application Update Status: {value}")`. So this will become: ```suggestion value = f"Spyder: {value}" logger.debug(f"Application Update Status: {value}") ``` def set_value(self, value): self.tooltip = self.BASE_TOOLTIP self.setVisible(True) self.update_tooltip() + value = f"Spyder: {value}" + logger.debug(f"Application Update Status: {value}") super().set_value(value) def get_tooltip(self):
codereview_new_python_data_9158
def _download_install(self): reporthook=self._progress_reporter) self._change_update_installation_status(status=INSTALLING) cmd = ('start' if os.name == 'nt' else 'open') - subprocess.run([cmd, destination], shell=True) except UpdateInstallationCancelledException: self._change_update_installation_status(status=CANCELLED) Seems that the command syntax was incorrect. `shell=True` requires a single string command; `shell=False` requires a list of command elements. We can either use ```suggestion subprocess.run(' '.join([cmd, destination]), shell=True) ``` Or ```suggestion subprocess.run([cmd, destination]) ``` Can you confirm that these also work for Windows? def _download_install(self): reporthook=self._progress_reporter) self._change_update_installation_status(status=INSTALLING) cmd = ('start' if os.name == 'nt' else 'open') + subprocess.run(' '.join([cmd, destination]), shell=True) except UpdateInstallationCancelledException: self._change_update_installation_status(status=CANCELLED)
codereview_new_python_data_9159
def _download_install(self): reporthook=self._progress_reporter) self._change_update_installation_status(status=INSTALLING) cmd = ('start' if os.name == 'nt' else 'open') - subprocess.run(' '.join([cmd, destination]), shell=True) except UpdateInstallationCancelledException: self._change_update_installation_status(status=CANCELLED) ```suggestion subprocess.run(' '.join([cmd, installer_path]), shell=True) ``` I thought this was fixed, but it wasn't. This needs to be updated. def _download_install(self): reporthook=self._progress_reporter) self._change_update_installation_status(status=INSTALLING) cmd = ('start' if os.name == 'nt' else 'open') + subprocess.run(' '.join([cmd, installer_path]), shell=True) except UpdateInstallationCancelledException: self._change_update_installation_status(status=CANCELLED)
codereview_new_python_data_9160
def _check_updates_ready(self): header = _("<b>Spyder {} is available!</b> ", "<i>(you have {})</i><br><br>").format( - latest_release,) footer = _( "For more information visit our " "<a href=\"{}\">installation guide</a>." I think here `__version__` is missing? So maybe @jsbautista this should be: ```suggestion latest_release, __version__) ``` def _check_updates_ready(self): header = _("<b>Spyder {} is available!</b> ", "<i>(you have {})</i><br><br>").format( + latest_release, __version__) footer = _( "For more information visit our " "<a href=\"{}\">installation guide</a>."
codereview_new_python_data_9161
FINISHED = _("Installation finished") PENDING = _("Update available") CHECKING = _("Checking for updates") -CANCELLED = _("Cancelled") INSTALL_INFO_MESSAGES = { - DOWNLOADING_INSTALLER: _("Downloading Spyder latest " - "release installer executable"), - INSTALLING: _("Installing Spyder latest release"), FINISHED: _("Spyder update installation finished"), - PENDING: _("An update is pending"), - CHECKING: _("Checking for updates"), - CANCELLED: _("Update cancelled") } Making this as a seperate comment so its easier to find on this long PR ```suggestion CANCELLED = _("Cancelled update") INSTALL_INFO_MESSAGES = { DOWNLOADING_INSTALLER: _("Downloading latest Spyder update"), INSTALLING: _("Installing Spyder update"), FINISHED: _("Spyder update installation finished"), PENDING: _("Spyder update available to download"), CHECKING: _("Checking for Spyder updates"), CANCELLED: _("Spyder update cancelled") ``` FINISHED = _("Installation finished") PENDING = _("Update available") CHECKING = _("Checking for updates") +CANCELLED = _("Cancelled update") INSTALL_INFO_MESSAGES = { + DOWNLOADING_INSTALLER: _("Downloading latest Spyder update"), + INSTALLING: _("Installing Spyder update"), FINISHED: _("Spyder update installation finished"), + PENDING: _("Spyder update available to download"), + CHECKING: _("Checking for Spyder updates"), + CANCELLED: _("Spyder update cancelled") }
codereview_new_python_data_9162
def _check_updates_ready(self): if update_available: self.application_update_status.set_status_pending() - header = _("<b>Spyder {} is available!</b> ", "<i>(you have {})</i><br><br>").format( latest_release, __version__) footer = _( Remove extra comma: ```suggestion header = _("<b>Spyder {} is available!</b> " ``` def _check_updates_ready(self): if update_available: self.application_update_status.set_status_pending() + header = _("<b>Spyder {} is available!</b> " "<i>(you have {})</i><br><br>").format( latest_release, __version__) footer = _(
codereview_new_python_data_9163
CANCELLED = _("Cancelled update") INSTALL_INFO_MESSAGES = { - DOWNLOADING_INSTALLER: _("Downloading latest Spyder update"), - INSTALLING: _("Installing Spyder update"), - FINISHED: _("Spyder update installation finished"), - PENDING: _("Spyder update available to download"), - CHECKING: _("Checking for Spyder updates"), CANCELLED: _("Spyder update cancelled") } ```suggestion DOWNLOADING_INSTALLER: _("Downloading Spyder {version}"), INSTALLING: _("Installing Spyder {version}"), FINISHED: _("Finished installing Spyder {version}"), PENDING: _("Spyder {version} available to download"), CHECKING: _("Checking for new Spyder version"), CANCELLED: _("Spyder update cancelled") ``` Will need changes (something like `message.format(version=version)` where this is used) but as discussed in our meeting, this will avoid redundancy with the other message and provide useful information. CANCELLED = _("Cancelled update") INSTALL_INFO_MESSAGES = { + DOWNLOADING_INSTALLER: _("Downloading Spyder {version}"), + INSTALLING: _("Installing Spyder {version}"), + FINISHED: _("Finished installing Spyder {version}"), + PENDING: _("Spyder {version} available to download"), + CHECKING: _("Checking for new Spyder version"), CANCELLED: _("Spyder update cancelled") }
codereview_new_python_data_9164
def __init__(self, parent): self.setLayout(general_layout) - def update_installation_status(self, status, latestVersion): """Update installation status (downloading, installing, finished).""" self._progress_label.setText(status) self.install_info.setText(INSTALL_INFO_MESSAGES[status].format( - version=latestVersion)) if status == INSTALLING: self._progress_bar.setRange(0, 0) self.cancel_button.setEnabled(False) Lets change the variable name here to `latest_version` instead of `latestVersion`. So: ```suggestion def update_installation_status(self, status, latest_version): """Update installation status (downloading, installing, finished).""" self._progress_label.setText(status) self.install_info.setText(INSTALL_INFO_MESSAGES[status].format( version=latest_version)) ``` def __init__(self, parent): self.setLayout(general_layout) + def update_installation_status(self, status, latest_version): """Update installation status (downloading, installing, finished).""" self._progress_label.setText(status) self.install_info.setText(INSTALL_INFO_MESSAGES[status].format( + version=latest_version)) if status == INSTALLING: self._progress_bar.setRange(0, 0) self.cancel_button.setEnabled(False)
codereview_new_python_data_9165
def get_cwd_of_new_client(): # Simulate a specific directory cwd_dir = str(tmpdir.mkdir('ipyconsole_cwd_test')) - ipyconsole.get_widget().current_working_directory = cwd_dir # Get cwd of new client and assert is the expected one assert get_cwd_of_new_client() == cwd_dir You will be able to use the function here as well def get_cwd_of_new_client(): # Simulate a specific directory cwd_dir = str(tmpdir.mkdir('ipyconsole_cwd_test')) + ipyconsole.get_widget().set_working_directory(cwd_dir) # Get cwd of new client and assert is the expected one assert get_cwd_of_new_client() == cwd_dir
codereview_new_python_data_9166
def _set_initial_cwd(self): if project_path is not None: cwd_path = project_path elif self.get_conf('console/use_cwd', section='workingdir'): - cwd_path = self.container.current_working_directory elif self.get_conf( 'console/use_fixed_directory', section='workingdir' It is best to leave the setter/getter for the working directory def _set_initial_cwd(self): if project_path is not None: cwd_path = project_path elif self.get_conf('console/use_cwd', section='workingdir'): + cwd_path = self.container.get_working_directory() elif self.get_conf( 'console/use_fixed_directory', section='workingdir'
codereview_new_python_data_9167
def interrupt_kernel(self): self.call_kernel(interrupt=True).raise_interrupt_signal() else: self._append_plain_text( - 'Cannot interrupt a non-spyder kernel I did not start.\n') def execute(self, source=None, hidden=False, interactive=False): """ ```suggestion 'Cannot interrupt a non-Spyder kernel I did not start.\n') ``` def interrupt_kernel(self): self.call_kernel(interrupt=True).raise_interrupt_signal() else: self._append_plain_text( + 'Cannot interrupt a non-Spyder kernel I did not start.\n') def execute(self, source=None, hidden=False, interactive=False): """
codereview_new_python_data_9168
def on_variable_explorer_teardown(self): self.get_widget().sig_show_namespace.disconnect( self.show_namespace_in_variable_explorer) def show_namespace_in_variable_explorer(self, namespace, shellwidget): """ Find the right variable explorer widget and show the namespace. ```suggestion # ---- Public API # ------------------------------------------------------------------------ ``` def on_variable_explorer_teardown(self): self.get_widget().sig_show_namespace.disconnect( self.show_namespace_in_variable_explorer) + # ---- Public API + # ------------------------------------------------------------------------ def show_namespace_in_variable_explorer(self, namespace, shellwidget): """ Find the right variable explorer widget and show the namespace.
codereview_new_python_data_9169
# Constants VALID_VARIABLE_CHARS = r"[^\w+*=¡!¿?'\"#$%&()/<>\-\[\]{}^`´;,|¬]*\w" # Max time before giving up when making a blocking call to the kernel CALL_KERNEL_TIMEOUT = 30 ```suggestion # Max time before giving up when making a blocking call to the kernel ``` # Constants VALID_VARIABLE_CHARS = r"[^\w+*=¡!¿?'\"#$%&()/<>\-\[\]{}^`´;,|¬]*\w" + # Max time before giving up when making a blocking call to the kernel CALL_KERNEL_TIMEOUT = 30
codereview_new_python_data_9170
def setup(self): # Tools actions if os.name == 'nt': - tip = ("Show and edit current user environment variables in " - "Windows registry (i.e. for all sessions)") else: - tip = ("Show current user environment variables (i.e. for all " - "sessions)") self.user_env_action = self.create_action( ApplicationActions.SpyderUserEnvVariables, _("Current user environment variables..."), ```suggestion tip = _("Show and edit current user environment variables in " "Windows registry (i.e. for all sessions)") ``` def setup(self): # Tools actions if os.name == 'nt': + tip = _("Show and edit current user environment variables in " + "Windows registry (i.e. for all sessions)") else: + tip = _("Show current user environment variables (i.e. for all " + "sessions)") self.user_env_action = self.create_action( ApplicationActions.SpyderUserEnvVariables, _("Current user environment variables..."),
codereview_new_python_data_9171
def setup(self): # Tools actions if os.name == 'nt': - tip = ("Show and edit current user environment variables in " - "Windows registry (i.e. for all sessions)") else: - tip = ("Show current user environment variables (i.e. for all " - "sessions)") self.user_env_action = self.create_action( ApplicationActions.SpyderUserEnvVariables, _("Current user environment variables..."), ```suggestion tip = _("Show current user environment variables (i.e. for all " "sessions)") ``` def setup(self): # Tools actions if os.name == 'nt': + tip = _("Show and edit current user environment variables in " + "Windows registry (i.e. for all sessions)") else: + tip = _("Show current user environment variables (i.e. for all " + "sessions)") self.user_env_action = self.create_action( ApplicationActions.SpyderUserEnvVariables, _("Current user environment variables..."),
codereview_new_python_data_9297
def _make_boundary(cls, text=None): def _compile_re(cls, s, flags): return re.compile(s, flags) class BytesGenerator(Generator): """Generates a bytes version of a Message object tree. Add a newline, for PEP8 compliance ```suggestion ``` def _make_boundary(cls, text=None): def _compile_re(cls, s, flags): return re.compile(s, flags) + class BytesGenerator(Generator): """Generates a bytes version of a Message object tree.
codereview_new_python_data_9298
from concurrent.futures import _base import queue import multiprocessing as mp from multiprocessing.queues import Queue import threading import weakref This one is actually necessary. It is later relied on when `mp.connection.wait` is called on L407. Without this import we are not guaranteed that `import multiprocessing as mp` causes `mp.connection` to exist. from concurrent.futures import _base import queue import multiprocessing as mp +import multiprocessing.connection from multiprocessing.queues import Queue import threading import weakref
codereview_new_python_data_9299
from queue import Empty, Full from . import connection from . import context _ForkingPickler = context.reduction.ForkingPickler How sure are you that this import doesn't have a sneaky side effect that's relied upon here? After all it's the C accelerator, things would presumably keep working without it, just slower, so passing tests might not be enough signal. from queue import Empty, Full +import _multiprocessing + from . import connection from . import context _ForkingPickler = context.reduction.ForkingPickler
codereview_new_python_data_9301
def expanduser(self): """ if (not (self._drv or self._root) and self._parts and self._parts[0][:1] == '~'): - homedir = self._flavour.expanduser(self) if homedir[:1] == "~": raise RuntimeError("Could not determine home directory.") - return self._from_parts([homedir]) return self Is this change (and the one below) necessary? Seems we shouldn't ever have a `~USERNAME` anywhere other than in the first part? We shouldn't have to format the string just to parse it again. def expanduser(self): """ if (not (self._drv or self._root) and self._parts and self._parts[0][:1] == '~'): + homedir = self._flavour.expanduser(self._parts[0]) if homedir[:1] == "~": raise RuntimeError("Could not determine home directory.") + drv, root, parts = self._parse_parts((homedir,)) + return self._from_parsed_parts(drv, root, parts + self._parts[1:]) return self
codereview_new_python_data_9305
def powtest(self, type): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 - for othertype in (int,): for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii ```suggestion for jj in range(-10, 0): ``` def powtest(self, type): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii
codereview_new_python_data_9306
def powtest(self, type): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 - for othertype in (int,): for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii ```suggestion for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii ``` def powtest(self, type): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii
codereview_new_python_data_9307
def powtest(self, type): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 - for othertype in (int,): for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii Mark is correct: (int,) used to be (int, float). If this line is deleted, other changes below must be applied. For some reason, I could not make them all at once. ```suggestion ``` def powtest(self, type): self.assertEqual(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) inv = pow(ii, -1) # inverse of ii
codereview_new_python_data_9326
def test_add_dir_getmember(self): self.add_dir_and_getmember('bar') self.add_dir_and_getmember('a'*101) def add_dir_and_getmember(self, name): def filter(tarinfo): tarinfo.uid = tarinfo.gid = 100 Please skip the test if hasattr(os, 'getuid') is false or hasattr(os, 'getgid') is false. def test_add_dir_getmember(self): self.add_dir_and_getmember('bar') self.add_dir_and_getmember('a'*101) + @unittest.skipUnless(hasattr(os, "getuid") and hasattr(os, "getgid"), + "Missing getuid or getgid implementation") def add_dir_and_getmember(self, name): def filter(tarinfo): tarinfo.uid = tarinfo.gid = 100
codereview_new_python_data_9327
def setswitchinterval(interval): interval = minimum_interval return sys.setswitchinterval(interval) def get_pagesize(): """Get size of a page in bytes.""" try: I'll change https://github.com/python/cpython/blob/main/Lib/test/memory_watchdog.py#L13 to get_pagesize in other pr. def setswitchinterval(interval): interval = minimum_interval return sys.setswitchinterval(interval) + def get_pagesize(): """Get size of a page in bytes.""" try:
codereview_new_python_data_9328
def test_async_and_await_are_keywords(self): def test_match_and_case_are_soft_keywords(self): self.assertIn("match", keyword.softkwlist) self.assertIn("case", keyword.softkwlist) - def test_keywords_are_sorted(self): self.assertSequenceEqual(sorted(keyword.kwlist), keyword.kwlist) Add new line, maybe delete line above, since '_' is most likely (soft) keyword to accidentally omit. ```suggestion self.assertIn("_", keyword.softkwlist) ``` def test_async_and_await_are_keywords(self): def test_match_and_case_are_soft_keywords(self): self.assertIn("match", keyword.softkwlist) self.assertIn("case", keyword.softkwlist) + self.assertIn("_", keyword.softkwlist) def test_keywords_are_sorted(self): self.assertSequenceEqual(sorted(keyword.kwlist), keyword.kwlist)
codereview_new_python_data_9331
def test_HTTPError_interface(self): def test_gh_98778(self): x = urllib.error.HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) self.assertEqual(getattr(x, "__notes__", ()), ()) - self.assertEqual(isinstance(x.fp.read(), bytes), True) def test_parse_proxy(self): parse_proxy_test_cases = [ ```suggestion self.assertIsInstance(x.fp.read(), bytes) ``` def test_HTTPError_interface(self): def test_gh_98778(self): x = urllib.error.HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) self.assertEqual(getattr(x, "__notes__", ()), ()) + self.assertIsInstance(x.fp.read(), bytes) def test_parse_proxy(self): parse_proxy_test_cases = [
codereview_new_python_data_9334
class Label: def assertInstructionsMatch(self, actual_, expected_): # get two lists where each entry is a label or # an instruction tuple. Normalize the labels to the - # instruction count of the target, adn compare the lists. self.assertIsInstance(actual_, list) self.assertIsInstance(expected_, list) ```suggestion # instruction count of the target, and compare the lists. ``` class Label: def assertInstructionsMatch(self, actual_, expected_): # get two lists where each entry is a label or # an instruction tuple. Normalize the labels to the + # instruction count of the target, and compare the lists. self.assertIsInstance(actual_, list) self.assertIsInstance(expected_, list)
codereview_new_python_data_9336
def __exit__(self, *args, **kwargs): # gh-101766: glboal cache should be cleaned-up # if there is no more _blocking_on for this thread. del _blocking_on[self.thread_id] class _DeadlockError(RuntimeError): Would it be worth completely undoing what `__enter__()` did? ```suggestion del _blocking_on[self.thread_id] del self.blocked_on ``` def __exit__(self, *args, **kwargs): # gh-101766: glboal cache should be cleaned-up # if there is no more _blocking_on for this thread. del _blocking_on[self.thread_id] + del self.blocked_on class _DeadlockError(RuntimeError):
codereview_new_python_data_9339
def is_integer(self): def as_integer_ratio(self): """Return a pair of integers, whose ratio is equal to the original Fraction. - The ratio is in lowest terms and with a positive denominator. """ return (self._numerator, self._denominator) ```suggestion The ratio is in lowest terms and has a positive denominator. ``` def is_integer(self): def as_integer_ratio(self): """Return a pair of integers, whose ratio is equal to the original Fraction. + The ratio is in lowest terms and has a positive denominator. """ return (self._numerator, self._denominator)
codereview_new_python_data_9341
def from_decimal(cls, dec): @classmethod def _from_pair(cls, numerator, denominator, /): - """Convert a pair of int's to a rational number, for internal use. The ratio of integers should be in lowest terms and the denominator is positive. Nitpick: I'd prefer `ints` to `int's`. def from_decimal(cls, dec): @classmethod def _from_pair(cls, numerator, denominator, /): + """Convert a pair of ints to a rational number, for internal use. The ratio of integers should be in lowest terms and the denominator is positive.
codereview_new_python_data_9342
def from_decimal(cls, dec): @classmethod def _from_pair(cls, numerator, denominator, /): - """Convert a pair of int's to a rational number, for internal use. The ratio of integers should be in lowest terms and the denominator is positive. Can we rename `_from_pair` to something more descriptive? How about `_from_coprime_pair` or `_from_coprime_ints`? def from_decimal(cls, dec): @classmethod def _from_pair(cls, numerator, denominator, /): + """Convert a pair of ints to a rational number, for internal use. The ratio of integers should be in lowest terms and the denominator is positive.
codereview_new_python_data_9345
def library_recipes(): dict( name="OpenSSL 1.1.1t", url="https://www.openssl.org/source/openssl-1.1.1t.tar.gz", - checksum='8dee9b24bdb1dcbf0c3d1e9b02fb8f6bf22165e807f45adeb7c9677536859d3b', buildrecipe=build_universal_openssl, configure=None, install=None, 3.9.x and earlier versions of build-installer.py only support md5 checksums here, change on its way def library_recipes(): dict( name="OpenSSL 1.1.1t", url="https://www.openssl.org/source/openssl-1.1.1t.tar.gz", + checksum='1cfee919e0eac6be62c88c5ae8bcd91e', buildrecipe=build_universal_openssl, configure=None, install=None,
codereview_new_python_data_9346
def library_recipes(): dict( name="OpenSSL 1.1.1t", url="https://www.openssl.org/source/openssl-1.1.1t.tar.gz", - checksum='8dee9b24bdb1dcbf0c3d1e9b02fb8f6bf22165e807f45adeb7c9677536859d3b', buildrecipe=build_universal_openssl, configure=None, install=None, 3.9.x and earlier versions of build-installer.py only support md5 checksums here, change on its way def library_recipes(): dict( name="OpenSSL 1.1.1t", url="https://www.openssl.org/source/openssl-1.1.1t.tar.gz", + checksum='1cfee919e0eac6be62c88c5ae8bcd91e', buildrecipe=build_universal_openssl, configure=None, install=None,
codereview_new_python_data_9347
def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec args = '{} /c "{}"'.format (comspec, args) ```suggestion if os.path.isabs(comspec): executable = comspec else: comspec = executable ``` def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec + else: + comspec = executable args = '{} /c "{}"'.format (comspec, args)
codereview_new_python_data_9348
def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec args = '{} /c "{}"'.format (comspec, args) ```suggestion if os.path.isabs(comspec): executable = comspec else: comspec = executable ``` def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec + else: + comspec = executable args = '{} /c "{}"'.format (comspec, args)
codereview_new_python_data_9349
def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec args = '{} /c "{}"'.format (comspec, args) ```suggestion if os.path.isabs(comspec): executable = comspec else: comspec = executable ``` def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec + else: + comspec = executable args = '{} /c "{}"'.format (comspec, args)
codereview_new_python_data_9350
def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec args = '{} /c "{}"'.format (comspec, args) ```suggestion if os.path.isabs(comspec): executable = comspec else: comspec = executable ``` def _execute_child(self, args, executable, preexec_fn, close_fds, raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') if os.path.isabs(comspec): executable = comspec + else: + comspec = executable args = '{} /c "{}"'.format (comspec, args)
codereview_new_python_data_9354
def _parse_parts(cls, parts): else: raise TypeError( "argument should be a str object or an os.PathLike " - "object returning str, not %r" - % type(path)) if altsep: path = path.replace(altsep, sep) drv, root, rel = cls._flavour.splitroot(path) ```suggestion "argument should be a str object or an os.PathLike " f"object where __fspath__ returns a str, not {type(path)!r}") ``` def _parse_parts(cls, parts): else: raise TypeError( "argument should be a str object or an os.PathLike " + f"object where __fspath__ returns a str, not {type(path)!r}") if altsep: path = path.replace(altsep, sep) drv, root, rel = cls._flavour.splitroot(path)
codereview_new_python_data_9358
def continue_in_while(): self.assertEqual(None, opcodes[1].argval) self.assertEqual('RETURN_VALUE', opcodes[2].opname) - def test_unloop_break_continue(self): - for stmt in ('break', 'continue'): - with self.subTest(stmt=stmt): - with self.assertRaises(SyntaxError) as err_ctx: - source = f"with object() as obj:\n {stmt}" - compile(source, f"<unloop_{stmt}>", "exec") - exc = err_ctx.exception - self.assertEqual(exc.lineno, 2) - def test_consts_in_conditionals(self): def and_true(x): return True and x There are some tests for break and continue outside loops in Lib/test/test_syntax.py, I think the lineno check could be added there. For instance, test_break_outside_loop calls self._check_error() but doesn't pass an expected lineno, though it could. And a similar test for continue could be added next to it. def continue_in_while(): self.assertEqual(None, opcodes[1].argval) self.assertEqual('RETURN_VALUE', opcodes[2].opname) def test_consts_in_conditionals(self): def and_true(x): return True and x
codereview_new_python_data_9359
class DynOptionMenu(OptionMenu): def __init__(self, master, variable, value, *values, **kwargs): highlightthickness = kwargs.pop('highlightthickness', None) OptionMenu.__init__(self, master, variable, value, *values, **kwargs) - self.config(highlightthickness=highlightthickness) self.variable = variable self.command = kwargs.get('command') For IDLE, I use dict syntax for single-attribute configure. ```suggestion self['highlightthickness'] = highlightthickness ``` class DynOptionMenu(OptionMenu): def __init__(self, master, variable, value, *values, **kwargs): highlightthickness = kwargs.pop('highlightthickness', None) OptionMenu.__init__(self, master, variable, value, *values, **kwargs) + self['highlightthickness'] = highlightthickness self.variable = variable self.command = kwargs.get('command')
codereview_new_python_data_9361
def commonpath(paths): try: - # The genericpath's isdir and isfile implementations uses os.stat internally. - # This is overkill on Windows - just pass the path to GetFileAttributesW - # and check the attribute from there. from nt import _isdir as isdir from nt import _isfile as isfile from nt import _exists as exists ```suggestion # The isdir(), isfile(), and exists() implementations in genericpath use # os.stat(). This is overkill on Windows. Use simpler builtin functions # if they are available. ``` def commonpath(paths): try: + # The isdir(), isfile(), and exists() implementations in genericpath use + # os.stat(). This is overkill on Windows. Use simpler builtin functions + # if they are available. from nt import _isdir as isdir from nt import _isfile as isfile from nt import _exists as exists
codereview_new_python_data_9362
def test_isjunction(self): @unittest.skipIf(sys.platform != 'win32', "drive letters are a windows concept") def test_isfile_driveletter(self): - current_drive = os.path.splitdrive(os.path.abspath(__file__))[0] + "\\" self.assertFalse(os.path.isfile(current_drive)) @unittest.skipIf(sys.platform != 'win32', "Fast paths are only for win32") The reason this is false is because a relative drive path like "C:" resolves to the working directory on the drive. Did you want to test a volume device path like `r'\\.\C:'` instead? def test_isjunction(self): @unittest.skipIf(sys.platform != 'win32', "drive letters are a windows concept") def test_isfile_driveletter(self): + current_drive = "\\\\.\\" + os.path.splitdrive(os.path.abspath(__file__))[0] self.assertFalse(os.path.isfile(current_drive)) @unittest.skipIf(sys.platform != 'win32', "Fast paths are only for win32")
codereview_new_python_data_9363
def test_isjunction(self): @unittest.skipIf(sys.platform != 'win32', "drive letters are a windows concept") def test_isfile_driveletter(self): - current_drive = "\\\\.\\" + os.path.splitdrive(os.path.abspath(__file__))[0] - self.assertFalse(os.path.isfile(current_drive)) @unittest.skipIf(sys.platform != 'win32', "Fast paths are only for win32") @cpython_only The test could be run on a UNC path, such as "\\\\localhost\\C$\\Source\cpython". In the latter case, the 'drive' of `__file__` would be "\\\\localhost\\C$". I'd use the `SystemDrive` environment variable, and skip the test if it doesn't exist or isn't a drive letter. ```suggestion drive = os.environ.get('SystemDrive') if drive is None or len(drive) != 2 or drive[1] != ':': raise unittest.SkipTest('SystemDrive is not defined or malformed') self.assertFalse(os.path.isfile('\\\\.\\' + drive)) ``` def test_isjunction(self): @unittest.skipIf(sys.platform != 'win32', "drive letters are a windows concept") def test_isfile_driveletter(self): + drive = os.environ.get('SystemDrive') + if drive is None or len(drive) != 2 or drive[1] != ':': + raise unittest.SkipTest('SystemDrive is not defined or malformed') + self.assertFalse(os.path.isfile('\\\\.\\' + drive)) @unittest.skipIf(sys.platform != 'win32', "Fast paths are only for win32") @cpython_only
codereview_new_python_data_9364
def commonpath(paths): # The isdir(), isfile(), islink() and exists() implementations in # genericpath use os.stat(). This is overkill on Windows. Use simpler # builtin functions if they are available. - from nt import _isdir as isdir - from nt import _isfile as isfile - from nt import _islink as islink - from nt import _exists as exists except ImportError: # Use genericpath.* as imported above pass ```suggestion from nt import _path_isdir as isdir from nt import _path_isfile as isfile from nt import _path_islink as islink from nt import _path_exists as exists ``` def commonpath(paths): # The isdir(), isfile(), islink() and exists() implementations in # genericpath use os.stat(). This is overkill on Windows. Use simpler # builtin functions if they are available. + from nt import _path_isdir as isdir + from nt import _path_isfile as isfile + from nt import _path_islink as islink + from nt import _path_exists as exists except ImportError: # Use genericpath.* as imported above pass
codereview_new_python_data_9368
def test_repr(self): def test_hash(self): self.assertEqual(hash(slice(5)), slice(5).__hash__()) self.assertNotEqual(slice(5), slice(6)) def test_cmp(self): s1 = slice(1, 2, 3) s2 = slice(1, 2, 3) Can we add more tests here? For example, test that `hash(slice(1, 2, []))` raises `TypeError` (to test the portion of the code where `PyObject_Hash()` fails). def test_repr(self): def test_hash(self): self.assertEqual(hash(slice(5)), slice(5).__hash__()) + self.assertEqual(hash(slice(1, 2)), slice(1, 2).__hash__()) + self.assertEqual(hash(slice(1, 2, 3)), slice(1, 2, 3).__hash__()) + self.assertEqual(hash((slice(4, 2), slice(2, 6))), (slice(4, 2), slice(2, 6)).__hash__()) self.assertNotEqual(slice(5), slice(6)) + with self.assertRaises(TypeError): + hash(slice(1, 2, [])) + + with self.assertRaises(TypeError): + hash(slice(4, {})) + def test_cmp(self): s1 = slice(1, 2, 3) s2 = slice(1, 2, 3)
codereview_new_python_data_9369
def test_hash(self): self.assertEqual(hash(slice(5)), slice(5).__hash__()) self.assertEqual(hash(slice(1, 2)), slice(1, 2).__hash__()) self.assertEqual(hash(slice(1, 2, 3)), slice(1, 2, 3).__hash__()) - self.assertEqual(hash((slice(4, 2), slice(2, 6))), (slice(4, 2), slice(2, 6)).__hash__()) self.assertNotEqual(slice(5), slice(6)) with self.assertRaises(TypeError): Thanks! I suggest removing these two lines. Comparison of slice objects and comparisons of tuple hashes can be left to `test_cmp()` and `test_tuple.py`, respectively. def test_hash(self): self.assertEqual(hash(slice(5)), slice(5).__hash__()) self.assertEqual(hash(slice(1, 2)), slice(1, 2).__hash__()) self.assertEqual(hash(slice(1, 2, 3)), slice(1, 2, 3).__hash__()) self.assertNotEqual(slice(5), slice(6)) with self.assertRaises(TypeError):