From 43f80d8f7c631dcdef0b81758871e09f9f357470 Mon Sep 17 00:00:00 2001 From: Mark Mayo Date: Wed, 12 Oct 2022 13:50:58 +1300 Subject: [PATCH] Fixed a series of pylint issues Ran tests afterwards, all passed --- .vscode/settings.json | 11 ++ gooey/gui/application/application.py | 14 +- gooey/gui/application/components.py | 11 +- gooey/gui/bootstrap.py | 3 +- gooey/gui/cli.py | 21 ++- gooey/gui/components/config.py | 3 +- gooey/gui/components/console.py | 4 +- gooey/gui/components/dialogs.py | 5 +- .../gui/components/filtering/prefix_filter.py | 8 +- gooey/gui/components/footer.py | 7 +- gooey/gui/components/header.py | 2 +- gooey/gui/components/menubar.py | 4 +- gooey/gui/components/modals.py | 1 - gooey/gui/components/mouse.py | 4 +- gooey/gui/components/options/options.py | 7 +- gooey/gui/components/options/validators.py | 9 +- gooey/gui/components/sidebar.py | 5 +- gooey/gui/components/tabbar.py | 2 +- .../components/util/wrapped_static_text.py | 2 +- gooey/gui/components/widgets/bases.py | 4 +- .../components/widgets/basictextconsole.py | 2 +- gooey/gui/components/widgets/checkbox.py | 4 +- gooey/gui/components/widgets/core/chooser.py | 12 +- .../gui/components/widgets/core/text_input.py | 2 +- .../components/widgets/dialogs/base_dialog.py | 77 +++++------ .../widgets/dialogs/calender_dialog.py | 9 +- .../components/widgets/dialogs/time_dialog.py | 7 +- gooey/gui/components/widgets/dropdown.py | 6 +- .../components/widgets/dropdown_filterable.py | 11 +- gooey/gui/components/widgets/listbox.py | 2 +- .../gui/components/widgets/numeric_fields.py | 2 - gooey/gui/components/widgets/password.py | 3 +- gooey/gui/components/widgets/radio_group.py | 2 +- .../gui/components/widgets/richtextconsole.py | 12 +- gooey/gui/components/widgets/textarea.py | 5 +- gooey/gui/components/widgets/textfield.py | 2 +- gooey/gui/constants.py | 1 - gooey/gui/containers/application.py | 39 +++--- gooey/gui/events.py | 1 - gooey/gui/formatters.py | 74 +++++------ gooey/gui/host.py | 1 - gooey/gui/image_repository.py | 2 - gooey/gui/lang/i18n.py | 27 ++-- gooey/gui/processor.py | 10 +- gooey/gui/pubsub.py | 4 +- gooey/gui/seeder.py | 4 +- gooey/gui/state.py | 18 ++- gooey/gui/three_to_four.py | 13 +- gooey/gui/util/casting.py | 14 +- gooey/gui/util/freeze.py | 3 +- gooey/gui/util/functional.py | 2 +- gooey/gui/util/quoting.py | 9 +- gooey/gui/util/time.py | 15 +-- gooey/gui/util/wx_util.py | 3 +- gooey/gui/validation.py | 5 +- gooey/gui/validators.py | 5 +- gooey/python_bindings/argparse_to_json.py | 78 ++++++----- gooey/python_bindings/cmd_args.py | 124 +++++++++--------- gooey/python_bindings/config_generator.py | 63 +++++---- gooey/python_bindings/constants.py | 1 - gooey/python_bindings/constraints.py | 13 +- gooey/python_bindings/control.py | 24 ++-- gooey/python_bindings/dynamics.py | 1 - gooey/python_bindings/gooey_decorator.py | 1 - gooey/python_bindings/gooey_parser.py | 17 ++- gooey/python_bindings/parameters.py | 3 +- gooey/python_bindings/parser_exceptions.py | 10 +- gooey/tests/__init__.py | 4 +- gooey/tests/all_widgets.py | 3 - gooey/tests/auto_start.py | 3 +- gooey/tests/dynamics/files/basic.py | 3 +- gooey/tests/dynamics/files/lifecycles.py | 3 +- gooey/tests/dynamics/test_dynamics.py | 1 - gooey/tests/dynamics/test_live_updates.py | 1 - gooey/tests/harness.py | 2 +- gooey/tests/integration/__init__.py | 2 +- gooey/tests/integration/integ_autostart.py | 9 +- .../tests/integration/integ_subparser_demo.py | 11 +- gooey/tests/integration/integ_validations.py | 6 - gooey/tests/integration/integ_widget_demo.py | 9 +- .../tests/integration/programs/auto_start.py | 3 +- .../tests/integration/programs/validations.py | 2 +- gooey/tests/integration/runner.py | 2 - gooey/tests/processor/files/ignore_break.py | 2 +- gooey/tests/processor/files/infinite_loop.py | 2 +- gooey/tests/processor/test_processor.py | 1 - gooey/tests/test_application.py | 2 +- gooey/tests/test_argparse_to_json.py | 9 +- gooey/tests/test_checkbox.py | 2 +- gooey/tests/test_cli.py | 2 +- gooey/tests/test_cmd_args.py | 2 +- gooey/tests/test_config_generator.py | 2 +- gooey/tests/test_constraints.py | 2 +- gooey/tests/test_control.py | 16 +-- gooey/tests/test_counter.py | 2 +- gooey/tests/test_decoration.py | 2 +- gooey/tests/test_dropdown.py | 5 +- gooey/tests/test_filtering.py | 6 +- gooey/tests/test_header.py | 2 +- gooey/tests/test_listbox.py | 2 +- gooey/tests/test_numeric_inputs.py | 4 +- gooey/tests/test_options.py | 2 +- gooey/tests/test_parent_inheritance.py | 2 +- gooey/tests/test_password.py | 2 +- gooey/tests/test_radiogroup.py | 4 +- gooey/tests/test_slider.py | 2 +- gooey/tests/test_textarea.py | 2 +- gooey/tests/test_textfield.py | 2 +- gooey/tests/test_time_remaining.py | 5 +- gooey/tests/test_util.py | 2 +- gooey/tests/tmmmmp.py | 2 +- gooey/util/functional.py | 12 +- setup.py | 2 +- tmp.txt | 1 + 114 files changed, 473 insertions(+), 566 deletions(-) create mode 100644 .vscode/settings.json create mode 100644 tmp.txt diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..40417f1e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "python.testing.unittestArgs": [ + "-v", + "-s", + "./gooey", + "-p", + "test*.py" + ], + "python.testing.pytestEnabled": false, + "python.testing.unittestEnabled": true +} \ No newline at end of file diff --git a/gooey/gui/application/application.py b/gooey/gui/application/application.py index 77254048..6fc6d19c 100644 --- a/gooey/gui/application/application.py +++ b/gooey/gui/application/application.py @@ -4,6 +4,10 @@ import six import wx # type: ignore +from rewx import components as c # type: ignore +from rewx import wsx # type: ignore +from rewx.core import Component, Ref # type: ignore + from gooey import Events from gooey.gui import events from gooey.gui import host @@ -28,9 +32,7 @@ from gooey.python_bindings.types import Try from gooey.util.functional import assoc from gooey.gui.util.time import Timing -from rewx import components as c # type: ignore -from rewx import wsx # type: ignore -from rewx.core import Component, Ref # type: ignore + class RGooey(Component): @@ -107,7 +109,7 @@ def component_did_mount(self): if self.state['fullscreen']: frame.ShowFullScreen(True) - if self.state['show_preview_warning'] and not 'unittest' in sys.modules.keys(): + if self.state['show_preview_warning'] and not 'unittest' in sys.modules: wx.MessageDialog(None, caption='YOU CAN DISABLE THIS MESSAGE', message=""" This is a preview build of 1.2.0! There may be instability or @@ -354,7 +356,3 @@ def render(self): [c.StaticLine, {'style': wx.LI_HORIZONTAL, 'flag': wx.EXPAND}], [RFooter, self.fprops(self.state)]]] ) - - - - diff --git a/gooey/gui/application/components.py b/gooey/gui/application/components.py index e74c5bce..04b2ba66 100644 --- a/gooey/gui/application/components.py +++ b/gooey/gui/application/components.py @@ -5,6 +5,11 @@ import wx # type: ignore from typing_extensions import TypedDict +from rewx import components as c # type: ignore +from rewx import wsx, mount, update # type: ignore +from rewx.core import Component, Ref # type: ignore +from rewx.widgets import set_basic_props # type: ignore + from gooey.gui.components.config import ConfigPage, TabbedConfigPage from gooey.gui.components.console import Console from gooey.gui.components.mouse import notifyMouseEvent @@ -15,10 +20,7 @@ from gooey.gui.state import present_time from gooey.gui.three_to_four import Constants from gooey.python_bindings import constants -from rewx import components as c # type: ignore -from rewx import wsx, mount, update # type: ignore -from rewx.core import Component, Ref # type: ignore -from rewx.widgets import set_basic_props # type: ignore + def attach_notifier(parent): @@ -331,4 +333,3 @@ def console(element, instance: Console): if 'show' in element['props']: instance.Show(element['props']['show']) return instance - diff --git a/gooey/gui/bootstrap.py b/gooey/gui/bootstrap.py index 040e903b..5ffd26ce 100644 --- a/gooey/gui/bootstrap.py +++ b/gooey/gui/bootstrap.py @@ -11,12 +11,13 @@ import wx.lib.inspection # type: ignore import wx.richtext # type: ignore import wx.xml # type: ignore +from rewx import render, create_element # type: ignore from gooey.gui import image_repository from gooey.gui.application.application import RGooey from gooey.gui.lang import i18n from gooey.util.functional import merge -from rewx import render, create_element # type: ignore + def run(build_spec): diff --git a/gooey/gui/cli.py b/gooey/gui/cli.py index 48455529..7a035f9e 100644 --- a/gooey/gui/cli.py +++ b/gooey/gui/cli.py @@ -3,8 +3,8 @@ from copy import deepcopy -from gooey.util.functional import compact from typing import List, Optional +from gooey.util.functional import compact from gooey.gui.constants import VALUE_PLACEHOLDER from gooey.gui.formatters import formatArgument @@ -18,7 +18,7 @@ validateField :: Target -> Command -> Array Arg -> Array Arg -> ArgId -> CliString completed :: Target -> Command -> FromState -> CliString failed :: Target -> Command -> FromState -> CliString -fieldAction :: Target -> Command -> +fieldAction :: Target -> Command -> ''' @@ -44,7 +44,7 @@ def formValidationCmd(target: str, subCommand: str, positionals: List[FieldValue positional_args = [cmdOrPlaceholderOrNone(x) for x in positionals] optional_args = [cmdOrPlaceholderOrNone(x) for x in optionals] command = subCommand if not subCommand == '::gooey/default' else '' - return u' '.join(compact([ + return ' '.join(compact([ target, command, *optional_args, @@ -62,7 +62,7 @@ def cliCmd(target: str, optional_args = [arg['cmd'] for arg in optionals] command = subCommand if not subCommand == '::gooey/default' else '' ignore_flag = '' if suppress_gooey_flag else '--ignore-gooey' - return u' '.join(compact([ + return ' '.join(compact([ target, command, *optional_args, @@ -81,15 +81,14 @@ def cmdOrPlaceholderOrNone(field: FieldValue) -> Optional[str]: # it actually being missing. if field['clitype'] == 'positional': return field['cmd'] or VALUE_PLACEHOLDER - elif field['clitype'] != 'positional' and field['meta']['required']: + if field['clitype'] != 'positional' and field['meta']['required']: # same rationale applies here. We supply the argument # along with a fixed placeholder (when relevant i.e. `store` # actions) return field['cmd'] or formatArgument(field['meta'], VALUE_PLACEHOLDER) - else: - # Optional values are, well, optional. So, like usual, we send - # them if present or drop them if not. - return field['cmd'] + # Optional values are, well, optional. So, like usual, we send + # them if present or drop them if not. + return field['cmd'] def buildCliString(target, subCommand, positional, optional, suppress_gooey_flag=False): @@ -100,7 +99,7 @@ def buildCliString(target, subCommand, positional, optional, suppress_gooey_flag arguments = ' '.join(compact(chain(optional, positionals))) if subCommand != '::gooey/default': - arguments = u'{} {}'.format(subCommand, arguments) + arguments = '{} {}'.format(subCommand, arguments) ignore_flag = '' if suppress_gooey_flag else '--ignore-gooey' - return u'{} {} {}'.format(target, ignore_flag, arguments) + return '{} {} {}'.format(target, ignore_flag, arguments) diff --git a/gooey/gui/components/config.py b/gooey/gui/components/config.py index 1c01b6e2..407ea342 100644 --- a/gooey/gui/components/config.py +++ b/gooey/gui/components/config.py @@ -15,7 +15,7 @@ class ConfigPage(ScrolledPanel): self_managed = True def __init__(self, parent, rawWidgets, buildSpec, *args, **kwargs): - super(ConfigPage, self).__init__(parent, *args, **kwargs) + super().__init__(parent, *args, **kwargs) self.SetupScrolling(scroll_x=False, scrollToTop=False) self.rawWidgets = rawWidgets @@ -273,4 +273,3 @@ def layoutComponent(self): def snapToErrorTab(self): pass - diff --git a/gooey/gui/components/console.py b/gooey/gui/components/console.py index 9938bc03..650110eb 100644 --- a/gooey/gui/components/console.py +++ b/gooey/gui/components/console.py @@ -34,7 +34,7 @@ def __init__(self, parent, buildSpec, **kwargs): self.getFontFace(), )) self.textbox.SetForegroundColour(self.buildSpec['terminal_font_color']) - + self.layoutComponent() self.Layout() self.Bind(wx.EVT_TEXT_URL, self.evtUrl, self.textbox) @@ -100,5 +100,3 @@ def layoutComponent(self): sizer.Add(self.textbox, 1, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 20) sizer.AddSpacer(20) self.SetSizer(sizer) - - diff --git a/gooey/gui/components/dialogs.py b/gooey/gui/components/dialogs.py index a042add1..8a33cc29 100644 --- a/gooey/gui/components/dialogs.py +++ b/gooey/gui/components/dialogs.py @@ -20,7 +20,7 @@ class HtmlDialog(wx.Dialog): def __init__(self, *args, **kwargs): caption = kwargs.pop('caption', '') html = kwargs.pop('html', '') - super(HtmlDialog, self).__init__(None, *args, **kwargs) + super().__init__(None, *args, **kwargs) wx.InitAllImageHandlers() @@ -35,6 +35,3 @@ def __init__(self, *args, **kwargs): sizer.Add(btnSizer, 0, wx.ALL | wx.EXPAND, 9) self.SetSizer(sizer) self.Layout() - - - diff --git a/gooey/gui/components/filtering/prefix_filter.py b/gooey/gui/components/filtering/prefix_filter.py index 79174130..eb564135 100644 --- a/gooey/gui/components/filtering/prefix_filter.py +++ b/gooey/gui/components/filtering/prefix_filter.py @@ -1,7 +1,8 @@ import re -import pygtrie as trie # type: ignore from functools import reduce +import pygtrie as trie # type: ignore + __ALL__ = ('PrefixTokenizers', 'PrefixSearch') @@ -38,7 +39,7 @@ def __init__(self, -class PrefixSearch(object): +class PrefixSearch(): """ A trie backed index for quickly finding substrings in a list of options. @@ -86,8 +87,7 @@ def tokenizeChoice(self, choice): return [token[i:] for token in tokens for i in range(len(token) - 2)] - else: - return tokens + return tokens def clean(self, text): return text.lower() if self.options.ignore_case else text diff --git a/gooey/gui/components/footer.py b/gooey/gui/components/footer.py index 4b70e6c6..5c4b2233 100644 --- a/gooey/gui/components/footer.py +++ b/gooey/gui/components/footer.py @@ -48,11 +48,10 @@ def updateTimeRemaining(self,*args,**kwargs): elapsed_time_value = kwargs.get('elapsed_time') if elapsed_time_value is None: return - elif estimate_time_remaining is not None: + if estimate_time_remaining is not None: self.time_remaining_text.SetLabel(f"{elapsed_time_value}<{estimate_time_remaining}") return - else: - self.time_remaining_text.SetLabel(f"{elapsed_time_value}") + self.time_remaining_text.SetLabel(f"{elapsed_time_value}") def updateProgressBar(self, *args, **kwargs): @@ -121,7 +120,7 @@ def _do_layout(self): h_sizer.Add(self.progress_bar, 1, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 20) - + h_sizer.Add(self.time_remaining_text,0,wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 20) h_sizer.AddStretchSpacer(1) diff --git a/gooey/gui/components/header.py b/gooey/gui/components/header.py index 5f1b3d39..4cc7cada 100644 --- a/gooey/gui/components/header.py +++ b/gooey/gui/components/header.py @@ -123,4 +123,4 @@ def bindMouseEvents(self): self._header.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) self._subheader.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) for image in self.images: - image.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) \ No newline at end of file + image.Bind(wx.EVT_LEFT_DOWN, notifyMouseEvent) diff --git a/gooey/gui/components/menubar.py b/gooey/gui/components/menubar.py index d6603f14..0f0fdf9d 100644 --- a/gooey/gui/components/menubar.py +++ b/gooey/gui/components/menubar.py @@ -14,7 +14,7 @@ class MenuBar(wx.MenuBar): """ def __init__(self, buildSpec, *args, **kwargs): - super(MenuBar,self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.buildSpec = buildSpec self.makeMenuItems(buildSpec.get('menu', [])) @@ -85,5 +85,3 @@ def spawnAboutDialog(self, item, *args, **kwargs): getattr(about, method)(item[field]) three_to_four.AboutBox(about) - - diff --git a/gooey/gui/components/modals.py b/gooey/gui/components/modals.py index 58004cfe..6f377d6d 100644 --- a/gooey/gui/components/modals.py +++ b/gooey/gui/components/modals.py @@ -45,4 +45,3 @@ def confirmExit(): def confirmForceStop(): result = showDialog(_('stop_task'), _('sure_you_want_to_stop'), wx.YES_NO | wx.ICON_WARNING) return result == DialogConstants.YES - diff --git a/gooey/gui/components/mouse.py b/gooey/gui/components/mouse.py index 0569f78d..667e5fba 100644 --- a/gooey/gui/components/mouse.py +++ b/gooey/gui/components/mouse.py @@ -17,7 +17,7 @@ from gooey.gui.pubsub import pub -import gooey.gui.events as events +from gooey.gui import events def notifyMouseEvent(event): """ @@ -25,4 +25,4 @@ def notifyMouseEvent(event): """ # TODO: is there ever a situation where this wouldn't be skipped..? event.Skip() - pub.send_message_sync(events.LEFT_DOWN, wxEvent=event) \ No newline at end of file + pub.send_message_sync(events.LEFT_DOWN, wxEvent=event) diff --git a/gooey/gui/components/options/options.py b/gooey/gui/components/options/options.py index 302ebe38..2d26f604 100644 --- a/gooey/gui/components/options/options.py +++ b/gooey/gui/components/options/options.py @@ -16,7 +16,7 @@ def _include_global_option_docs(f): Combines docstrings for options available to all widget types. """ - _doc = """:param initial_value: Sets the initial value in the UI. + _doc = """:param initial_value: Sets the initial value in the UI. """ f.__doc__ = (f.__doc__ or '') + _doc return f @@ -26,7 +26,7 @@ def _include_chooser_msg_wildcard_docs(f): Combines the basic Chooser options (wildard, message) docsstring with the wrapped function's doc string. """ - _doc = """:param wildcard: Sets the wildcard, which can contain multiple file types, for + _doc = """:param wildcard: Sets the wildcard, which can contain multiple file types, for example: "BMP files (.bmp)|.bmp|GIF files (.gif)|.gif" :param message: Sets the message that will be displayed on the dialog. """ @@ -38,7 +38,7 @@ def _include_choose_dir_file_docs(f): Combines the basic Chooser options (wildard, message) docsstring with the wrapped function's doc string. """ - _doc = """:param default_dir: The default directory selected when the dialog spawns + _doc = """:param default_dir: The default directory selected when the dialog spawns :param default_file: The default filename used in the dialog """ f.__doc__ = (f.__doc__ or '') + _doc @@ -331,4 +331,3 @@ def _clean(options): cleaned = {k: v for k, v in options.items() if v is not None and k != "layout_options"} return {**options.get('layout_options', {}), **cleaned} - diff --git a/gooey/gui/components/options/validators.py b/gooey/gui/components/options/validators.py index b6cfc149..7f7b0ee6 100644 --- a/gooey/gui/components/options/validators.py +++ b/gooey/gui/components/options/validators.py @@ -4,7 +4,7 @@ from gooey.gui.components.filtering.prefix_filter import OperatorType -class SuperBool(object): +class SuperBool(): """ A boolean which keeps with it the rationale for when it is false. @@ -117,12 +117,11 @@ def is_valid_color(value): """Must be either a valid hex string or RGB list""" if is_str(value): return is_hex_string(value) - elif is_tuple_or_list(value): + if is_tuple_or_list(value): return (is_tuple_or_list(value) and is_three_channeled(value) and has_valid_channel_values(value)) - else: - return is_str_or_coll(value) + return is_str_or_coll(value) validators = { @@ -197,5 +196,3 @@ def validate(pred, value): # print(is_valid_color([255, 244, 256])) # print(non_empty_string('asdf') and non_empty_string('asdf')) # validate(is_valid_color, 1234) - - diff --git a/gooey/gui/components/sidebar.py b/gooey/gui/components/sidebar.py index 2132d856..268f91ad 100644 --- a/gooey/gui/components/sidebar.py +++ b/gooey/gui/components/sidebar.py @@ -9,7 +9,7 @@ class Sidebar(wx.Panel): of the wx.Notebook class (which wants to control everything) """ def __init__(self, parent, buildSpec, configPanels, *args, **kwargs): - super(Sidebar, self).__init__(parent, *args, **kwargs) + super().__init__(parent, *args, **kwargs) self._parent = parent self.buildSpec = buildSpec self.configPanels = configPanels @@ -81,6 +81,3 @@ def layoutLeftSide(self): container.AddSpacer(20) self.leftPanel.SetSizer(container) return self.leftPanel - - - diff --git a/gooey/gui/components/tabbar.py b/gooey/gui/components/tabbar.py index 02b3327a..a446441e 100644 --- a/gooey/gui/components/tabbar.py +++ b/gooey/gui/components/tabbar.py @@ -7,7 +7,7 @@ class Tabbar(wx.Panel): def __init__(self, parent, buildSpec, configPanels, *args, **kwargs): - super(Tabbar, self).__init__(parent, *args, **kwargs) + super().__init__(parent, *args, **kwargs) self._parent = parent self.notebook = wx.Notebook(self, style=wx.BK_DEFAULT) self.buildSpec = buildSpec diff --git a/gooey/gui/components/util/wrapped_static_text.py b/gooey/gui/components/util/wrapped_static_text.py index 301cb373..5d80e389 100644 --- a/gooey/gui/components/util/wrapped_static_text.py +++ b/gooey/gui/components/util/wrapped_static_text.py @@ -30,7 +30,7 @@ class AutoWrappedStaticText(wx.StaticText): def __init__(self, parent, *args, **kwargs): self.target = kwargs.pop('target', None) - super(AutoWrappedStaticText, self).__init__(parent, *args, **kwargs) + super().__init__(parent, *args, **kwargs) self.label = kwargs.get('label') self.Bind(wx.EVT_SIZE, self.OnSize) self.parent = parent diff --git a/gooey/gui/components/widgets/bases.py b/gooey/gui/components/widgets/bases.py index 11a19bf4..772c9a05 100644 --- a/gooey/gui/components/widgets/bases.py +++ b/gooey/gui/components/widgets/bases.py @@ -63,7 +63,7 @@ class TextContainer(BaseWidget): widget_class = None # type: ignore def __init__(self, parent, widgetInfo, *args, **kwargs): - super(TextContainer, self).__init__(parent, *args, **kwargs) + super().__init__(parent, *args, **kwargs) self.info = widgetInfo self._id = widgetInfo['id'] @@ -183,7 +183,7 @@ def getUiState(self) -> t.FormField: def syncUiState(self, state: FormField): # type: ignore self.widget.setValue(state['value']) # type: ignore self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') def getValue(self) -> t.FieldValue: diff --git a/gooey/gui/components/widgets/basictextconsole.py b/gooey/gui/components/widgets/basictextconsole.py index 5840524b..95a43fa3 100644 --- a/gooey/gui/components/widgets/basictextconsole.py +++ b/gooey/gui/components/widgets/basictextconsole.py @@ -2,4 +2,4 @@ class BasicTextConsole(wx.TextCtrl): def __init__(self, parent): - super(BasicTextConsole, self).__init__(parent, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH | wx.TE_AUTO_URL ) + super().__init__(parent, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH | wx.TE_AUTO_URL ) diff --git a/gooey/gui/components/widgets/checkbox.py b/gooey/gui/components/widgets/checkbox.py index 219db409..df741773 100644 --- a/gooey/gui/components/widgets/checkbox.py +++ b/gooey/gui/components/widgets/checkbox.py @@ -71,7 +71,7 @@ def syncUiState(self, state: t.Checkbox): # type: ignore checkbox.Enable(state['enabled']) self.Show(state['visible']) self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') @@ -125,4 +125,4 @@ def arrange(self, *args, **kwargs): layout.Add(hsizer, 1, wx.EXPAND) layout.AddSpacer(2) - return layout \ No newline at end of file + return layout diff --git a/gooey/gui/components/widgets/core/chooser.py b/gooey/gui/components/widgets/core/chooser.py index 03ba649c..7d2c1186 100644 --- a/gooey/gui/components/widgets/core/chooser.py +++ b/gooey/gui/components/widgets/core/chooser.py @@ -1,7 +1,7 @@ -import wx # type: ignore -import wx.lib.agw.multidirdialog as MDD # type: ignore import os import re +import wx # type: ignore +import wx.lib.agw.multidirdialog as MDD # type: ignore from gooey.gui.components.widgets.core.text_input import TextInput from gooey.gui.components.widgets.dialogs.calender_dialog import CalendarDlg @@ -31,7 +31,7 @@ class Chooser(wx.Panel): 'pathsep': str } def __init__(self, parent, *args, **kwargs): - super(Chooser, self).__init__(parent) + super().__init__(parent) self.options = parent._options buttonLabel = kwargs.pop('label', _('browse')) self.widget = TextInput(self, *args, **kwargs) @@ -153,7 +153,7 @@ class DateChooser(Chooser): """ Launches a date picker which returns an ISO Date """ def __init__(self, *args, **kwargs): defaults = {'label': _('choose_date')} - super(DateChooser, self).__init__(*args, **merge(kwargs, defaults)) + super().__init__(*args, **merge(kwargs, defaults)) def getDialog(self): return CalendarDlg(self) @@ -163,7 +163,7 @@ class TimeChooser(Chooser): """ Launches a time picker which returns and ISO Time """ def __init__(self, *args, **kwargs): defaults = {'label': _('choose_time')} - super(TimeChooser, self).__init__(*args, **merge(kwargs, defaults)) + super().__init__(*args, **merge(kwargs, defaults)) def getDialog(self): return TimeDlg(self) @@ -174,7 +174,7 @@ class ColourChooser(Chooser): def __init__(self, *args, **kwargs): defaults = {'label': _('choose_colour'), 'style': wx.TE_RICH} - super(ColourChooser, self).__init__(*args, **merge(kwargs, defaults)) + super().__init__(*args, **merge(kwargs, defaults)) def setValue(self, value): colour = wx.Colour(value) diff --git a/gooey/gui/components/widgets/core/text_input.py b/gooey/gui/components/widgets/core/text_input.py index a0fccb48..c94630bf 100644 --- a/gooey/gui/components/widgets/core/text_input.py +++ b/gooey/gui/components/widgets/core/text_input.py @@ -7,7 +7,7 @@ class TextInput(wx.Panel): def __init__(self, parent, *args, **kwargs): - super(TextInput, self).__init__(parent) + super().__init__(parent) self.widget = wx.TextCtrl(self, *args, **kwargs) dt = FileDrop(self.widget) self.widget.SetDropTarget(dt) diff --git a/gooey/gui/components/widgets/dialogs/base_dialog.py b/gooey/gui/components/widgets/dialogs/base_dialog.py index ffde6a30..ed6e02fd 100644 --- a/gooey/gui/components/widgets/dialogs/base_dialog.py +++ b/gooey/gui/components/widgets/dialogs/base_dialog.py @@ -1,53 +1,56 @@ -from gooey.gui.lang.i18n import _ - import wx # type: ignore +from gooey.gui.lang.i18n import _ from gooey.gui.three_to_four import Constants + class BaseDialog(wx.Dialog): - """ - Common base for CalendarDlg and TimeDlg. - """ - def __init__(self, parent, pickerClass, pickerGetter, localizedPickerLabel): - wx.Dialog.__init__(self, parent, title=localizedPickerLabel) + """ + Common base for CalendarDlg and TimeDlg. + """ - self.SetBackgroundColour('#ffffff') + def __init__(self, parent, pickerClass, pickerGetter, localizedPickerLabel): + wx.Dialog.__init__(self, parent, title=localizedPickerLabel) - self.ok_button = wx.Button(self, wx.ID_OK, label=_('ok')) - self.picker = pickerClass(self, style=Constants.WX_DP_DROPDOWN) - self.pickerGetter = pickerGetter + self.SetBackgroundColour('#ffffff') - vertical_container = wx.BoxSizer(wx.VERTICAL) - vertical_container.AddSpacer(10) - vertical_container.Add(self.picker, 0, wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER, 15) + self.ok_button = wx.Button(self, wx.ID_OK, label=_('ok')) + self.picker = pickerClass(self, style=Constants.WX_DP_DROPDOWN) + self.pickerGetter = pickerGetter - vertical_container.AddSpacer(10) - button_sizer = wx.BoxSizer(wx.HORIZONTAL) - button_sizer.AddStretchSpacer(1) - button_sizer.Add(self.ok_button, 0) + vertical_container = wx.BoxSizer(wx.VERTICAL) + vertical_container.AddSpacer(10) + vertical_container.Add(self.picker, 0, wx.LEFT | + wx.RIGHT | wx.ALIGN_CENTER, 15) - vertical_container.Add(button_sizer, 0, wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER, 15) - vertical_container.AddSpacer(20) - self.SetSizerAndFit(vertical_container) + vertical_container.AddSpacer(10) + button_sizer = wx.BoxSizer(wx.HORIZONTAL) + button_sizer.AddStretchSpacer(1) + button_sizer.Add(self.ok_button, 0) - self.Bind(wx.EVT_BUTTON, self.onOkButton, self.ok_button) + vertical_container.Add(button_sizer, 0, wx.LEFT | + wx.RIGHT | wx.ALIGN_CENTER, 15) + vertical_container.AddSpacer(20) + self.SetSizerAndFit(vertical_container) - def onOkButton(self, event): - self.EndModal(wx.ID_OK) - event.Skip() + self.Bind(wx.EVT_BUTTON, self.onOkButton, self.ok_button) - def onCancelButton(self, event): - try: - return None - except: - self.Close() + def onOkButton(self, event): + self.EndModal(wx.ID_OK) + event.Skip() - def GetPath(self): - """ - Return the value chosen in the picker. - The method is called GetPath() instead of getPath() to emulate the WX Pickers API. - This allows the Chooser class to work same way with native WX dialogs or children of BaseDialog. - """ + def onCancelButton(self, event): + try: + return None + except Exception: + self.Close() + + def GetPath(self): + """ + Return the value chosen in the picker. + The method is called GetPath() instead of getPath() to emulate the WX Pickers API. + This allows the Chooser class to work same way with native WX dialogs or children of BaseDialog. + """ - return self.pickerGetter(self.picker) + return self.pickerGetter(self.picker) diff --git a/gooey/gui/components/widgets/dialogs/calender_dialog.py b/gooey/gui/components/widgets/dialogs/calender_dialog.py index f664fd2e..88f30dd4 100644 --- a/gooey/gui/components/widgets/dialogs/calender_dialog.py +++ b/gooey/gui/components/widgets/dialogs/calender_dialog.py @@ -1,13 +1,12 @@ - - -from .base_dialog import BaseDialog from gooey.gui.three_to_four import Classes from gooey.gui.lang.i18n import _ +from .base_dialog import BaseDialog + class CalendarDlg(BaseDialog): def __init__(self, parent): - super(CalendarDlg, self).__init__(parent, + super().__init__(parent, pickerClass=Classes.DatePickerCtrl, pickerGetter=lambda datepicker: datepicker.GetValue().FormatISODate(), - localizedPickerLabel=_('select_date')) \ No newline at end of file + localizedPickerLabel=_('select_date')) diff --git a/gooey/gui/components/widgets/dialogs/time_dialog.py b/gooey/gui/components/widgets/dialogs/time_dialog.py index 3b1af27c..c79ceabd 100644 --- a/gooey/gui/components/widgets/dialogs/time_dialog.py +++ b/gooey/gui/components/widgets/dialogs/time_dialog.py @@ -1,12 +1,11 @@ - -from .base_dialog import BaseDialog from gooey.gui.three_to_four import Classes from gooey.gui.lang.i18n import _ +from .base_dialog import BaseDialog class TimeDlg(BaseDialog): - def __init__(self, parent): - super(TimeDlg, self).__init__(parent, + def __init__(self, parent): + super().__init__(parent, pickerClass=Classes.TimePickerCtrl, pickerGetter=lambda datepicker: datepicker.GetValue().FormatISOTime(), localizedPickerLabel=_('select_time')) diff --git a/gooey/gui/components/widgets/dropdown.py b/gooey/gui/components/widgets/dropdown.py index f43d4a29..cbf7199d 100644 --- a/gooey/gui/components/widgets/dropdown.py +++ b/gooey/gui/components/widgets/dropdown.py @@ -1,8 +1,8 @@ from contextlib import contextmanager -from gooey.gui.components.widgets.bases import TextContainer -import wx # type: ignore +import wx # type: ignore +from gooey.gui.components.widgets.bases import TextContainer from gooey.gui import formatters from gooey.gui.lang.i18n import _ from gooey.python_bindings import types as t @@ -52,7 +52,7 @@ def syncUiState(self, state: FormField): if state['selected'] is not None: # type: ignore self.setValue(state['selected']) # type: ignore self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') def getUiState(self) -> t.FormField: widget: wx.ComboBox = self.widget diff --git a/gooey/gui/components/widgets/dropdown_filterable.py b/gooey/gui/components/widgets/dropdown_filterable.py index 4babdf1b..1673271c 100644 --- a/gooey/gui/components/widgets/dropdown_filterable.py +++ b/gooey/gui/components/widgets/dropdown_filterable.py @@ -3,7 +3,7 @@ import wx # type: ignore import wx.html # type: ignore -import gooey.gui.events as events +from gooey.gui import events from gooey.gui.components.filtering.prefix_filter import PrefixSearch from gooey.gui.components.mouse import notifyMouseEvent from gooey.gui.components.widgets.dropdown import Dropdown @@ -56,7 +56,7 @@ def __init__(self, *args, **kwargs): # this inheritance garbage is broken. self.listbox = None self.model = None - super(FilterableDropdown, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.SetDoubleBuffered(True) def interpretState(self, model): @@ -128,7 +128,7 @@ def syncUiState(self, state: t.DropdownFilterable): # type: ignore if state['value'] is not None: self.setValue(state['value']) self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') def OnGetItem(self, n): return self.model.suggestions[n] @@ -225,7 +225,7 @@ def estimateBestSize(self): class VirtualizedListBox(wx.html.HtmlListBox): def __init__(self, *args, **kwargs): - super(VirtualizedListBox, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.SetItemCount(1) def OnGetItem(self, n): @@ -234,7 +234,7 @@ def OnGetItem(self, n): -class FilterableDropdownModel(object): +class FilterableDropdownModel(): """ The model/state for the FilterableDropdown. While this is still one big ball of mutation (hard to get away from in WX), it serves the purpose @@ -368,4 +368,3 @@ def Create(self, parent): def GetControl(self): return self.lc - diff --git a/gooey/gui/components/widgets/listbox.py b/gooey/gui/components/widgets/listbox.py index c3f4143b..e70a5f25 100644 --- a/gooey/gui/components/widgets/listbox.py +++ b/gooey/gui/components/widgets/listbox.py @@ -51,4 +51,4 @@ def syncUiState(self, state: t.Listbox): # type: ignore for string in state['selected']: widget.SetStringSelection(string) self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') diff --git a/gooey/gui/components/widgets/numeric_fields.py b/gooey/gui/components/widgets/numeric_fields.py index c5bb1c77..25ce169f 100644 --- a/gooey/gui/components/widgets/numeric_fields.py +++ b/gooey/gui/components/widgets/numeric_fields.py @@ -71,5 +71,3 @@ def getUiState(self) -> t.FormField: enabled=self.IsEnabled(), visible=self.IsShown() ) - - diff --git a/gooey/gui/components/widgets/password.py b/gooey/gui/components/widgets/password.py index 1c0e82a1..a5daa027 100644 --- a/gooey/gui/components/widgets/password.py +++ b/gooey/gui/components/widgets/password.py @@ -8,8 +8,7 @@ class PasswordField(TextField): widget_class = PasswordInput # type: ignore def __init__(self, *args, **kwargs): - super(PasswordField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def getUiState(self) -> t.FormField: # type: ignore return t.PasswordField(**super().getUiState()) # type: ignore - diff --git a/gooey/gui/components/widgets/radio_group.py b/gooey/gui/components/widgets/radio_group.py index 7be743ad..bbf1d398 100644 --- a/gooey/gui/components/widgets/radio_group.py +++ b/gooey/gui/components/widgets/radio_group.py @@ -14,7 +14,7 @@ class RadioGroup(BaseWidget): """ def __init__(self, parent, widgetInfo, *args, **kwargs): - super(RadioGroup, self).__init__(parent, *args, **kwargs) + super().__init__(parent, *args, **kwargs) self._parent = parent self.info = widgetInfo self._id = widgetInfo['id'] diff --git a/gooey/gui/components/widgets/richtextconsole.py b/gooey/gui/components/widgets/richtextconsole.py index 66a9f22a..72ab266e 100644 --- a/gooey/gui/components/widgets/richtextconsole.py +++ b/gooey/gui/components/widgets/richtextconsole.py @@ -1,7 +1,7 @@ +import re import wx # type: ignore import wx.richtext # type: ignore import colored # type: ignore -import re from gooey.python_bindings import types as t @@ -62,12 +62,12 @@ def __init__(self, parent): wxcolor = wx.Colour(int(hex[1:3],16), int(hex[3:5],16), int(hex[5:],16), alpha=wx.ALPHA_OPAQUE) # NB : we use a default parameter to force the evaluation of the binding self.actionsMap[escSeq] = lambda bindedColor=wxcolor: self.BeginTextColour(bindedColor) - + self.Bind(wx.EVT_MOUSEWHEEL, self.onMouseWheel) def PreprocessAndWriteText(self, content): - """Write text into console, while capturing URLs and making + """Write text into console, while capturing URLs and making them blue, underlined, and clickable. """ textStream=iter(re.split(self.regex_urls, content)) @@ -76,7 +76,7 @@ def PreprocessAndWriteText(self, content): for plaintext in textStream: url=next(textStream, None) self.WriteText(plaintext) - if url: + if url: self.BeginTextColour(self.url_colour) self.BeginUnderline() self.BeginURL(url) @@ -84,7 +84,7 @@ def PreprocessAndWriteText(self, content): self.EndURL() self.EndUnderline() self.EndTextColour() - + def AppendText(self, content): """ wx method overridden to capture the terminal control character and translate them into wx styles. @@ -122,4 +122,4 @@ def onMouseWheel(self, event): return self.SetFontScale(self.GetFontScale() * r, True) else: - event.Skip() + event.Skip() diff --git a/gooey/gui/components/widgets/textarea.py b/gooey/gui/components/widgets/textarea.py index 27dc42af..8c13380e 100644 --- a/gooey/gui/components/widgets/textarea.py +++ b/gooey/gui/components/widgets/textarea.py @@ -1,6 +1,7 @@ import os -import wx # type: ignore from functools import reduce +import wx # type: ignore + from gooey.gui.components.widgets.core.text_input import MultilineTextInput from gooey.gui.components.widgets.textfield import TextField @@ -41,7 +42,7 @@ def formatOutput(self, metatdata, value: str): def syncUiState(self, state: FormField): self.setValue(state['value']) # type: ignore self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') def getUiState(self) -> t.FormField: return t.TextField( diff --git a/gooey/gui/components/widgets/textfield.py b/gooey/gui/components/widgets/textfield.py index 5b5955a1..3e6cab4c 100644 --- a/gooey/gui/components/widgets/textfield.py +++ b/gooey/gui/components/widgets/textfield.py @@ -27,5 +27,5 @@ def syncUiState(self, state: t.TextField): # type: ignore textctr.Enable(state['enabled']) self.Show(state['visible']) self.error.SetLabel(state['error'] or '') - self.error.Show(state['error'] is not None and state['error'] is not '') + self.error.Show(state['error'] is not None and state['error'] != '') self.Layout() diff --git a/gooey/gui/constants.py b/gooey/gui/constants.py index 51f8e321..3cf0f13e 100644 --- a/gooey/gui/constants.py +++ b/gooey/gui/constants.py @@ -1,4 +1,3 @@ VALUE_PLACEHOLDER = '::gooey/placeholder' RADIO_PLACEHOLDER = '::gooey/radio-placeholder' - diff --git a/gooey/gui/containers/application.py b/gooey/gui/containers/application.py index b232f0ec..46928106 100644 --- a/gooey/gui/containers/application.py +++ b/gooey/gui/containers/application.py @@ -4,33 +4,35 @@ import queue import sys import threading +from threading import Lock +from threading import Thread, get_ident from contextlib import contextmanager from functools import wraps from json import JSONDecodeError from pprint import pprint from subprocess import CalledProcessError -from threading import Thread, get_ident + from typing import Mapping, Dict, Type, Iterable + +import signal + import six import wx # type: ignore -from gooey.gui.state import FullGooeyState -from gooey.python_bindings.types import PublicGooeyState +from typing_extensions import TypedDict from rewx.widgets import set_basic_props +from rewx import wsx, render, create_element, mount, update +from rewx import components as c +from wx.adv import TaskBarIcon # type: ignore + +from gooey.gui.state import FullGooeyState +from gooey.python_bindings.types import PublicGooeyState from gooey.gui.components.mouse import notifyMouseEvent from gooey.gui.state import initial_state, present_time, form_page, ProgressEvent, TimingEvent from gooey.gui import state as s from gooey.gui.three_to_four import Constants -from rewx.core import Component, Ref, updatewx, patch -from typing_extensions import TypedDict - -from rewx import wsx, render, create_element, mount, update -from rewx import components as c -from wx.adv import TaskBarIcon # type: ignore -import signal - from gooey import Events from gooey.gui import cli from gooey.gui import events @@ -56,7 +58,7 @@ from gooey.gui import host -from threading import Lock + from gooey.util.functional import associnMany @@ -68,7 +70,7 @@ class GooeyApplication(wx.Frame): """ def __init__(self, buildSpec, *args, **kwargs): - super(GooeyApplication, self).__init__(None, *args, **kwargs) + super().__init__(None, *args, **kwargs) self._state = {} self.buildSpec = buildSpec @@ -291,9 +293,8 @@ def fetchDynamicValidations(self) -> Try[Mapping[str, str]]: cmd.positionals, cmd.optionals ), self.buildSpec['encoding']) - else: - # shim response if nothing to do. - return Success({}) + # shim response if nothing to do. + return Success({}) def getCommandDetails(self) -> CommandDetails: @@ -438,9 +439,3 @@ def showForceStopped(self): else: self.showSuccess() self.header.setSubtitle(_('finished_forced_quit')) - - - - - - diff --git a/gooey/gui/events.py b/gooey/gui/events.py index 9e35727d..5bc30b7d 100644 --- a/gooey/gui/events.py +++ b/gooey/gui/events.py @@ -26,4 +26,3 @@ USER_INPUT = wx.Window.NewControlId() LEFT_DOWN = wx.Window.NewControlId() - diff --git a/gooey/gui/formatters.py b/gooey/gui/formatters.py index 84bec598..cd4ad7cb 100644 --- a/gooey/gui/formatters.py +++ b/gooey/gui/formatters.py @@ -11,15 +11,13 @@ def value(field: FormField): if field['type'] in ['Checkbox', 'BlockCheckbox']: return field['checked'] # type: ignore - elif field['type'] in ['Dropdown', 'Listbox', 'Counter']: + if field['type'] in ['Dropdown', 'Listbox', 'Counter']: return field['selected'] # type: ignore - elif field['type'] == 'RadioGroup': + if field['type'] == 'RadioGroup': if field['selected'] is not None: # type: ignore return value(field['options'][field['selected']]) # type: ignore - else: - return None - else: - return field['value'] # type: ignore + return None + return field['value'] # type: ignore def add_placeholder(field: FormField, placeholder=VALUE_PLACEHOLDER): @@ -34,9 +32,9 @@ def add_placeholder(field: FormField, placeholder=VALUE_PLACEHOLDER): # way of passing a placeholder without even MORE monket patching # of the user's parser to rewrite the action type return assoc(field, 'checked', True) - elif field['type'] in ['Dropdown', 'Listbox', 'Counter']: + if field['type'] in ['Dropdown', 'Listbox', 'Counter']: return assoc(field, 'selected', placeholder) - elif field['type'] == 'RadioGroup': + if field['type'] == 'RadioGroup': # We arbitrarily attach a placeholder for first RadioGroup option # and mark it as the selected one. return { @@ -47,35 +45,32 @@ def add_placeholder(field: FormField, placeholder=VALUE_PLACEHOLDER): *field['options'][1:] # type: ignore ] } - else: - return assoc(field, 'value', placeholder) + return assoc(field, 'value', placeholder) def formatArgument(item: EnrichedItem): if item['type'] in ['Checkbox', 'CheckBox', 'BlockCheckbox']: return checkbox(item['data'], value(item['field'])) - elif item['type'] == 'MultiFileChooser': + if item['type'] == 'MultiFileChooser': return multiFileChooser(item['data'], value(item['field'])) - elif item['type'] == 'Textarea': + if item['type'] == 'Textarea': return textArea(item['data'], value(item['field'])) - elif item['type'] == 'CommandField': + if item['type'] == 'CommandField': return textArea(item['data'], value(item['field'])) - elif item['type'] == 'Counter': + if item['type'] == 'Counter': return counter(item['data'], value(item['field'])) - elif item['type'] == 'Dropdown': + if item['type'] == 'Dropdown': return dropdown(item['data'], value(item['field'])) - elif item['type'] == 'Listbox': + if item['type'] == 'Listbox': return listbox(item['data'], value(item['field'])) - elif item['type'] == 'RadioGroup': + if item['type'] == 'RadioGroup': selected = item['field']['selected'] # type: ignore if selected is not None: formField = item['field']['options'][selected] # type: ignore argparseDefinition = item['data']['widgets'][selected] # type: ignore return formatArgument(assoc(argparseDefinition, 'field', formField)) # type: ignore - else: - return None - else: - return general(item['data'], value(item['field'])) + return None + return general(item['data'], value(item['field'])) def placeholder(item: EnrichedItem): @@ -89,22 +84,20 @@ def checkbox(metadata, value): def multiFileChooser(metadata, value): paths = ' '.join(quote(x) for x in value.split(os.pathsep) if x) if metadata['commands'] and paths: - return u'{} {}'.format(metadata['commands'][0], paths) + return '{} {}'.format(metadata['commands'][0], paths) return paths or None def textArea(metadata, value): if metadata['commands'] and value: return '{} {}'.format(metadata['commands'][0], quote(value.encode('unicode_escape'))) - else: - return quote(value.encode('unicode_escape')) if value else '' + return quote(value.encode('unicode_escape')) if value else '' def commandField(metadata, value): if metadata['commands'] and value: - return u'{} {}'.format(metadata['commands'][0], value) - else: - return value or None + return '{} {}'.format(metadata['commands'][0], value) + return value or None def counter(metatdata, value): @@ -123,17 +116,15 @@ def counter(metatdata, value): def dropdown(metadata, value): if value == 'Select Option': return None - elif metadata['commands'] and value: - return u'{} {}'.format(metadata['commands'][0], quote(value)) - else: - return quote(value) if value else '' + if metadata['commands'] and value: + return '{} {}'.format(metadata['commands'][0], quote(value)) + return quote(value) if value else '' def listbox(meta, value): if meta['commands'] and value: - return u'{} {}'.format(meta['commands'][0], ' '.join(map(quote, value))) - else: - return ' '.join(map(quote, value)) if value else '' + return '{} {}'.format(meta['commands'][0], ' '.join(map(quote, value))) + return ' '.join(map(quote, value)) if value else '' def general(metadata, value): @@ -142,12 +133,9 @@ def general(metadata, value): v = quote(value) else: v = value - return u'{0} {1}'.format(metadata['commands'][0], v) - else: - if not value: - return None - elif not metadata.get('nargs'): - return quote(value) - else: - return value - + return '{0} {1}'.format(metadata['commands'][0], v) + if not value: + return None + if not metadata.get('nargs'): + return quote(value) + return value diff --git a/gooey/gui/host.py b/gooey/gui/host.py index e75efbb1..f6b3b2ec 100644 --- a/gooey/gui/host.py +++ b/gooey/gui/host.py @@ -42,4 +42,3 @@ def work(): callback(result) thread = Thread(target=work) thread.start() - diff --git a/gooey/gui/image_repository.py b/gooey/gui/image_repository.py index 3fa31da8..7ed76893 100644 --- a/gooey/gui/image_repository.py +++ b/gooey/gui/image_repository.py @@ -48,5 +48,3 @@ def collectOverrides(targetDir, filenames): def resolvePaths(dirname, filenames): return {key: os.path.join(dirname, filename) for key, filename in filenames.items()} - - diff --git a/gooey/gui/lang/i18n.py b/gooey/gui/lang/i18n.py index 3d6df19e..0f639ec4 100644 --- a/gooey/gui/lang/i18n.py +++ b/gooey/gui/lang/i18n.py @@ -15,20 +15,23 @@ _DICTIONARY = None + def load(language_dir, filename, encoding): - ''' Open and return the supplied json file ''' - global _DICTIONARY - try: - json_file = filename + '.json' - with io.open(os.path.join(language_dir, json_file), 'r', encoding=encoding) as f: - _DICTIONARY = json.load(f) - except IOError: - raise IOError('{0} Language file not found at location {1}. ' - 'Make sure that your translation file is in the ' - 'listed language directory'.format(filename.title(), language_dir)) + ''' Open and return the supplied json file ''' + global _DICTIONARY + try: + json_file = filename + '.json' + with io.open(os.path.join(language_dir, json_file), 'r', encoding=encoding) as f: + _DICTIONARY = json.load(f) + except IOError: + raise IOError('{0} Language file not found at location {1}. ' + 'Make sure that your translation file is in the ' + 'listed language directory'.format(filename.title(), language_dir)) + def translate(key): - return _DICTIONARY.get(key, '(Translate me!) {}'.format(key)) + return _DICTIONARY.get(key, '(Translate me!) {}'.format(key)) + def _(key): - return translate(key) + return translate(key) diff --git a/gooey/gui/processor.py b/gooey/gui/processor.py index d43cda6a..defbab9d 100644 --- a/gooey/gui/processor.py +++ b/gooey/gui/processor.py @@ -23,7 +23,7 @@ creationflag = 0 -class ProcessController(object): +class ProcessController(): @classmethod def of(cls, params: GooeyParams): @@ -96,7 +96,7 @@ def run(self, command): stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=self.shell_execution, env=env, creationflags=creationflag) - except: + except Exception: self._process = subprocess.Popen( command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, @@ -146,8 +146,7 @@ def _calculate_progress(self, match): ''' if not self.progress_expr: return safe_float(match.group(1)) - else: - return self._eval_progress(match) + return self._eval_progress(match) def _eval_progress(self, match): ''' @@ -158,6 +157,5 @@ def _eval_progress(self, match): _locals["x"] = [safe_float(x) for x in match.groups()] try: return int(eval(self.progress_expr, {}, _locals)) - except: + except Exception: return None - diff --git a/gooey/gui/pubsub.py b/gooey/gui/pubsub.py index 0557244f..adc4acd8 100644 --- a/gooey/gui/pubsub.py +++ b/gooey/gui/pubsub.py @@ -1,10 +1,10 @@ -import wx # type: ignore from collections import defaultdict +import wx # type: ignore __ALL__ = ['pub'] -class PubSub(object): +class PubSub(): """ A super simplified clone of Wx.lib.pubsub since it doesn't exist on linux """ diff --git a/gooey/gui/seeder.py b/gooey/gui/seeder.py index 659f99cc..17d18aa8 100644 --- a/gooey/gui/seeder.py +++ b/gooey/gui/seeder.py @@ -31,8 +31,6 @@ def communicate(cmd, encoding) -> Try: out, err = proc.communicate() if out and proc.poll() == 0: return Success(deserialize_inbound(out, encoding)) - else: - return Failure(CalledProcessError(proc.returncode, cmd, output=out, stderr=err)) + return Failure(CalledProcessError(proc.returncode, cmd, output=out, stderr=err)) except JSONDecodeError as e: return Failure(e) - diff --git a/gooey/gui/state.py b/gooey/gui/state.py index 83b460e7..4e2d5565 100644 --- a/gooey/gui/state.py +++ b/gooey/gui/state.py @@ -114,7 +114,7 @@ def activeFormState(state: FullGooeyState): def buildInvocationCmd(state: FullGooeyState): pieces = cli_pieces(state) - return u' '.join(compact([ + return ' '.join(compact([ pieces.target, pieces.subcommand, *pieces.optionals, @@ -141,7 +141,7 @@ def buildOnCompleteCmd(state: FullGooeyState, was_success: bool): pieces = cli_pieces(state) serializedForm = json.dumps({'active_form': activeFormState(state)}) b64ecoded = b64encode(serializedForm.encode('utf-8')) - return u' '.join(compact([ + return ' '.join(compact([ pieces.target, pieces.subcommand, *pieces.optionals, @@ -168,15 +168,14 @@ def cmdOrPlaceholderOrNone(item: EnrichedItem) -> Optional[str]: # it actually being missing. if item['cli_type'] == 'positional': return formatArgument(item) or VALUE_PLACEHOLDER - elif item['cli_type'] != 'positional' and item['required']: + if item['cli_type'] != 'positional' and item['required']: # same rationale applies here. We supply the argument # along with a fixed placeholder (when relevant i.e. `store` # actions) return formatArgument(item) or formatArgument(assoc(item, 'field', add_placeholder(item['field']))) - else: - # Optional values are, well, optional. So, like usual, we send - # them if present or drop them if not. - return formatArgument(item) + # Optional values are, well, optional. So, like usual, we send + # them if present or drop them if not. + return formatArgument(item) @@ -412,7 +411,6 @@ def present_time(timer): elapsed_time_value = timer['elapsed_time'] if elapsed_time_value is None: return '' - elif estimate_time_remaining is not None: + if estimate_time_remaining is not None: return f'{elapsed_time_value}<{estimate_time_remaining}' - else: - return f'{elapsed_time_value}' + return f'{elapsed_time_value}' diff --git a/gooey/gui/three_to_four.py b/gooey/gui/three_to_four.py index 5f4c8e80..f5b48fc0 100644 --- a/gooey/gui/three_to_four.py +++ b/gooey/gui/three_to_four.py @@ -37,32 +37,27 @@ class Classes: def imageFromBitmap(bitmap): if isLatestVersion: return bitmap.ConvertToImage() - else: - return wx.ImageFromBitmap(bitmap) + return wx.ImageFromBitmap(bitmap) def bitmapFromImage(image): if isLatestVersion: return wx.Bitmap(image) - else: - return wx.BitmapFromImage(image) + return wx.BitmapFromImage(image) def bitmapFromBufferRGBA(im, rgba): if isLatestVersion: return wx.Bitmap.FromBufferRGBA(im.size[0], im.size[1], rgba) - else: - return wx.BitmapFromBufferRGBA(im.size[0], im.size[1], rgba) + return wx.BitmapFromBufferRGBA(im.size[0], im.size[1], rgba) def AboutDialog(): if isLatestVersion: return wx.adv.AboutDialogInfo() - else: - return wx.AboutDialogInfo() + return wx.AboutDialogInfo() def AboutBox(aboutDialog): return (wx.adv.AboutBox(aboutDialog) if isLatestVersion else wx.AboutBox(aboutDialog)) - diff --git a/gooey/gui/util/casting.py b/gooey/gui/util/casting.py index 8e905445..ffaff631 100644 --- a/gooey/gui/util/casting.py +++ b/gooey/gui/util/casting.py @@ -1,15 +1,15 @@ def safe_int(n): - return _safe_cast(int, n) + return _safe_cast(int, n) + def safe_float(n): - return _safe_cast(float, n) + return _safe_cast(float, n) def _safe_cast(_type, val): - try: - return _type(val) - except ValueError: - return None - + try: + return _type(val) + except ValueError: + return None diff --git a/gooey/gui/util/freeze.py b/gooey/gui/util/freeze.py index b3eb4d41..aabda556 100644 --- a/gooey/gui/util/freeze.py +++ b/gooey/gui/util/freeze.py @@ -43,5 +43,4 @@ def localResourcePath(path): if is_frozen(): basedir = getattr(sys, '_MEIPASS', None) return os.path.join(basedir or sys.executable, path) - else: - return os.path.join(os.getcwd(), path) + return os.path.join(os.getcwd(), path) diff --git a/gooey/gui/util/functional.py b/gooey/gui/util/functional.py index d0d2a70b..d9374c2a 100644 --- a/gooey/gui/util/functional.py +++ b/gooey/gui/util/functional.py @@ -24,7 +24,7 @@ def merge_dictionaries(x,y): y = {} try: return {**x,**y} - except: + except Exception: z = x.copy() z.update(y) return z diff --git a/gooey/gui/util/quoting.py b/gooey/gui/util/quoting.py index 8a1d1fe7..da2029cc 100644 --- a/gooey/gui/util/quoting.py +++ b/gooey/gui/util/quoting.py @@ -2,9 +2,8 @@ if sys.platform.startswith("win"): - def quote(value): - return u'"{}"'.format(u'{}'.format(value).replace(u'"', u'""')) + def quote(value): + return '"{}"'.format('{}'.format(value).replace('"', '""')) else: # POSIX shell - def quote(value): - return u"'{}'".format(u'{}'.format(value).replace(u"'", u"'\\''")) - + def quote(value): + return "'{}'".format('{}'.format(value).replace("'", "'\\''")) diff --git a/gooey/gui/util/time.py b/gooey/gui/util/time.py index f6644634..15665b0f 100644 --- a/gooey/gui/util/time.py +++ b/gooey/gui/util/time.py @@ -5,7 +5,7 @@ from gooey.gui.pubsub import pub from gooey.gui import events -class Timing(object): +class Timing(): def __init__(self, parent): self.startTime = 0 @@ -18,10 +18,10 @@ def __init__(self, parent): def _updateEstimate(self, *args, **kwargs): prog = kwargs.get('progress') - if(not prog): + if not prog: self.estimatedRemaining = None return - if(prog > 0): + if prog > 0: self.estimatedRemaining = estimate_time_remaining(prog,self.startTime) def publishTime(self, *args, **kwargs): @@ -58,9 +58,8 @@ def format_interval(timeValue): h, m = divmod(mins, 60) if h: return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s) - else: - return '{0:02d}:{1:02d}'.format(m, s) - except: + return '{0:02d}:{1:02d}'.format(m, s) + except Exception: return None def get_elapsed_time(startTime): @@ -79,7 +78,7 @@ def estimate_time_remaining(progress,startTime): # https://github.com/tqdm/tqdm/blob/0cd9448b2bc08125e74538a2aea6af42ee1a7b6f/tqdm/std.py#L392 # https://github.com/tqdm/tqdm/blob/0cd9448b2bc08125e74538a2aea6af42ee1a7b6f/tqdm/std.py#L417 _rate = progress / get_elapsed_time(startTime) - return ((100 - progress) / _rate) + return (100 - progress) / _rate def get_current_time(): """ @@ -91,6 +90,6 @@ def get_current_time(): try: from time import perf_counter return perf_counter() - except: + except Exception: import timeit return timeit.default_timer() diff --git a/gooey/gui/util/wx_util.py b/gooey/gui/util/wx_util.py index 06b0ab8f..a648f40a 100644 --- a/gooey/gui/util/wx_util.py +++ b/gooey/gui/util/wx_util.py @@ -3,9 +3,10 @@ """ from functools import wraps -import wx # type: ignore from contextlib import contextmanager +import wx # type: ignore + from gooey.gui.three_to_four import Constants diff --git a/gooey/gui/validation.py b/gooey/gui/validation.py index 28f94ad7..a2578a34 100644 --- a/gooey/gui/validation.py +++ b/gooey/gui/validation.py @@ -25,6 +25,5 @@ def fetchDynamicValidations(self) -> Try[Mapping[str, str]]: cmd.positionals, cmd.optionals ), self.buildSpec['encoding']) - else: - # shim response if nothing to do. - return Success({}) \ No newline at end of file + # shim response if nothing to do. + return Success({}) diff --git a/gooey/gui/validators.py b/gooey/gui/validators.py index de808a4b..46aef932 100644 --- a/gooey/gui/validators.py +++ b/gooey/gui/validators.py @@ -8,8 +8,5 @@ def runValidator(f, value) -> bool: """ try: return f(value) - except: + except Exception: return False - - - diff --git a/gooey/python_bindings/argparse_to_json.py b/gooey/python_bindings/argparse_to_json.py index a209aef5..9238603f 100644 --- a/gooey/python_bindings/argparse_to_json.py +++ b/gooey/python_bindings/argparse_to_json.py @@ -57,7 +57,6 @@ class UnsupportedConfiguration(Exception): pass - # TODO: merge the default foreground and bg colors from the # baseline build_spec item_default = { @@ -138,7 +137,8 @@ def process(parser, widget_dict, options, group_defaults): mutex_groups = parser._mutually_exclusive_groups raw_action_groups = [extract_groups(group, group_defaults) for group in parser._action_groups if group._group_actions] - corrected_action_groups = reapply_mutex_groups(mutex_groups, raw_action_groups) + corrected_action_groups = reapply_mutex_groups( + mutex_groups, raw_action_groups) return categorize2(strip_empty(corrected_action_groups), widget_dict, options) @@ -159,15 +159,14 @@ def iter_parsers(parser): ''' Iterate over name, parser pairs ''' try: return get_subparser(parser._actions).choices.items() - except: + except Exception: return iter([('::gooey/default', parser)]) def get_subparser_help(parser): if isinstance(parser, GooeyParser): return getattr(parser.parser, 'usage', '') - else: - return getattr(parser, 'usage', '') + return getattr(parser, 'usage', '') def extract_groups(action_group, group_defaults): @@ -212,11 +211,9 @@ def handle_option_merge(group_defaults, incoming_options, title): req_cols = getin(group_defaults, ['legacy', 'required_cols'], 2) new_defaults = assoc(group_defaults, 'columns', req_cols) return merge(new_defaults, incoming_options) - else: - opt_cols = getin(group_defaults, ['legacy', 'optional_cols'], 2) - new_defaults = assoc(group_defaults, 'columns', opt_cols) - return merge(new_defaults, incoming_options) - + opt_cols = getin(group_defaults, ['legacy', 'optional_cols'], 2) + new_defaults = assoc(group_defaults, 'columns', opt_cols) + return merge(new_defaults, incoming_options) def apply_default_rewrites(spec): @@ -257,7 +254,7 @@ def swap_actions(actions): actions[targetindex] = mutexgroup # remove the duplicated individual actions actions = [action for action in actions - if action not in mutex_actions] + if action not in mutex_actions] return actions return [group.update({'items': swap_actions(group['items'])}) or group @@ -271,7 +268,7 @@ def categorize2(groups, widget_dict, options): 'items': list(categorize(group['items'], widget_dict, options)), 'groups': categorize2(group['groups'], widget_dict, options), 'description': group['description'], - 'options': merge(defaults ,group['options']) + 'options': merge(defaults, group['options']) } for group in groups] @@ -286,7 +283,7 @@ def categorize(actions, widget_dict, options): elif is_standard(action): yield action_to_json(action, _get_widget(action, 'TextField'), options) - + elif is_writemode_file(action): yield action_to_json(action, _get_widget(action, 'FileSaver'), options) @@ -300,7 +297,8 @@ def categorize(actions, widget_dict, options): yield action_to_json(action, _get_widget(action, 'CheckBox'), options) elif is_counter(action): - _json = action_to_json(action, _get_widget(action, 'Counter'), options) + _json = action_to_json( + action, _get_widget(action, 'Counter'), options) # pre-fill the 'counter' dropdown _json['data']['choices'] = list(map(str, range(0, 11))) yield _json @@ -319,7 +317,7 @@ def is_required(action): through `nargs` being '*' or '?' ''' return not isinstance(action, _SubParsersAction) and ( - action.required == True and action.nargs not in ['*', '?']) + action.required is True and action.nargs not in ['*', '?']) def is_mutex(action): @@ -354,13 +352,16 @@ def is_choice(action): ''' action with choices supplied ''' return action.choices + def is_file(action): ''' action with FileType ''' return isinstance(action.type, argparse.FileType) + def is_readmode_file(action): return is_file(action) and 'r' in action.type._mode + def is_writemode_file(action): # FileType uses the same modes as the builtin `open` # as such, all modes that aren't explicitly `r` (which is @@ -368,6 +369,7 @@ def is_writemode_file(action): # making a FileChooser a good choice. return is_file(action) and 'r' not in action.type._mode + def is_version(action): return isinstance(action, _VersionAction) or issubclass(type(action), _VersionAction) @@ -398,7 +400,6 @@ def is_flag(action): or issubclass(type(action), (_StoreTrueAction, _StoreFalseAction, _StoreConstAction))) - def is_counter(action): """ _actions which are of type _CountAction """ return isinstance(action, _CountAction) @@ -417,19 +418,19 @@ def choose_name(name, subparser): def build_radio_group(mutex_group, widget_group, options): - dests = [action.dest for action in mutex_group._group_actions] - return { - 'id': 'group_' + '_'.join(dests), - 'type': 'RadioGroup', - 'cli_type': 'optional', - 'group_name': 'Choose Option', - 'required': mutex_group.required, - 'options': merge(item_default, getattr(mutex_group, 'gooey_options', {})), - 'data': { - 'commands': [action.option_strings for action in mutex_group._group_actions], - 'widgets': list(categorize(mutex_group._group_actions, widget_group, options)) + dests = [action.dest for action in mutex_group._group_actions] + return { + 'id': 'group_' + '_'.join(dests), + 'type': 'RadioGroup', + 'cli_type': 'optional', + 'group_name': 'Choose Option', + 'required': mutex_group.required, + 'options': merge(item_default, getattr(mutex_group, 'gooey_options', {})), + 'data': { + 'commands': [action.option_strings for action in mutex_group._group_actions], + 'widgets': list(categorize(mutex_group._group_actions, widget_group, options)) + } } - } def action_to_json(action, widget, options): @@ -455,15 +456,14 @@ def action_to_json(action, widget, options): }, }) - if (options.get(action.dest) or {}).get('initial_value') != None: + if (options.get(action.dest) or {}).get('initial_value') is not None: value = options[action.dest]['initial_value'] - options[action.dest]['initial_value'] = handle_initial_values(action, widget, value) + options[action.dest]['initial_value'] = handle_initial_values( + action, widget, value) default = handle_initial_values(action, widget, action.default) if default == argparse.SUPPRESS: default = None - - final_options = merge(base, options.get(action.dest) or {}) validate_gooey_options(action, widget, final_options) @@ -503,7 +503,7 @@ def validate_gooey_options(action, widget, options): debug which `gooey_option` key had an issue in a large program. That said "better is the enemy of done." This is good enough for now. It'll be - a TODO: better validation + a TODO: better validation """ errors = collect_errors(validators, options) if errors: @@ -513,8 +513,8 @@ def validate_gooey_options(action, widget, options): def choose_cli_type(action): return 'positional' \ - if action.required and not action.option_strings \ - else 'optional' + if action.required and not action.option_strings \ + else 'optional' def coerce_default(default, widget): @@ -562,6 +562,7 @@ def coerse_nargs_list(default): """ return ' '.join('"{}"'.format(x) for x in default) + def is_widget(name): def equals(action, widget): return widget == name @@ -586,7 +587,6 @@ def is_list_based_nargs(action): return isinstance(action.nargs, int) or action.nargs in {'*', '+', '...'} - def clean_list_defaults(default_values): """ Listbox's default's can be passed as a single value @@ -623,8 +623,7 @@ def safe_string(value): """ if value is None or isinstance(value, bool): return value - else: - return str(value) + return str(value) def coerce_str(value): @@ -634,7 +633,6 @@ def coerce_str(value): return str(value) if value is not None else value - def this_is_a_comment(action, widget): """ TODO: @@ -681,4 +679,4 @@ def this_is_a_comment(action, widget): 'TextField', 'Textarea', 'PasswordField', - ] \ No newline at end of file + ] diff --git a/gooey/python_bindings/cmd_args.py b/gooey/python_bindings/cmd_args.py index 4d0e5e30..a51b936a 100644 --- a/gooey/python_bindings/cmd_args.py +++ b/gooey/python_bindings/cmd_args.py @@ -9,71 +9,73 @@ from argparse import _SubParsersAction + def parse_cmd_args(self, args=None): - def prepare_to_read_cmd_args(item): - ''' - Before reading the command-line arguments, we need to fudge a few things: - 1. If there are subparsers, we need a dest in order to know in which - subparser the command-line values should be stored. - 2. Any required argument or mutex group needs to be made not required, - otherwise it will be compulsory to enter those values on the command - line. - We save the everything as it was before the fudge, so we can restore later. - ''' - for action in item._actions: - if isinstance(action, _SubParsersAction): - action.save_dest = action.dest - if not action.dest: - action.dest = '_subparser' - else: - action.save_required = action.required - action.required = False - action.save_nargs = action.nargs - if action.nargs == '+': - action.nargs = '*' - elif action.nargs is None: - action.nargs = '?' + def prepare_to_read_cmd_args(item): + ''' + Before reading the command-line arguments, we need to fudge a few things: + 1. If there are subparsers, we need a dest in order to know in which + subparser the command-line values should be stored. + 2. Any required argument or mutex group needs to be made not required, + otherwise it will be compulsory to enter those values on the command + line. + We save the everything as it was before the fudge, so we can restore later. + ''' + for action in item._actions: + if isinstance(action, _SubParsersAction): + action.save_dest = action.dest + if not action.dest: + action.dest = '_subparser' + else: + action.save_required = action.required + action.required = False + action.save_nargs = action.nargs + if action.nargs == '+': + action.nargs = '*' + elif action.nargs is None: + action.nargs = '?' - for mutex_group in item._mutually_exclusive_groups: - mutex_group.save_required = mutex_group.required - mutex_group.required = False + for mutex_group in item._mutually_exclusive_groups: + mutex_group.save_required = mutex_group.required + mutex_group.required = False - def overwrite_default_values(item, cmd_args): - ''' - Subsistute arguments provided on the command line in the place of the - default values provided to argparse. - ''' - for action in item._actions: - if isinstance(action, _SubParsersAction): - subparser_arg = getattr(cmd_args, action.dest, None) - if subparser_arg: - overwrite_default_values(action.choices[subparser_arg], cmd_args) - else: - dest = getattr(action, 'dest', None) - if dest: - cmd_arg = getattr(cmd_args, dest, None) - if cmd_arg: - action.default = cmd_arg + def overwrite_default_values(item, cmd_args): + ''' + Subsistute arguments provided on the command line in the place of the + default values provided to argparse. + ''' + for action in item._actions: + if isinstance(action, _SubParsersAction): + subparser_arg = getattr(cmd_args, action.dest, None) + if subparser_arg: + overwrite_default_values( + action.choices[subparser_arg], cmd_args) + else: + dest = getattr(action, 'dest', None) + if dest: + cmd_arg = getattr(cmd_args, dest, None) + if cmd_arg: + action.default = cmd_arg - def restore_original_configuration(item): - ''' - Restore the old values as they were to start with. - ''' - for action in item._actions: - if isinstance(action, _SubParsersAction): - action.dest = action.save_dest - del action.save_dest - else: - action.required = action.save_required - del action.save_required - action.nargs = action.save_nargs - del action.save_nargs + def restore_original_configuration(item): + ''' + Restore the old values as they were to start with. + ''' + for action in item._actions: + if isinstance(action, _SubParsersAction): + action.dest = action.save_dest + del action.save_dest + else: + action.required = action.save_required + del action.save_required + action.nargs = action.save_nargs + del action.save_nargs - for mutex_group in item._mutually_exclusive_groups: - mutex_group.required = mutex_group.save_required - del mutex_group.save_required + for mutex_group in item._mutually_exclusive_groups: + mutex_group.required = mutex_group.save_required + del mutex_group.save_required - prepare_to_read_cmd_args(self) - overwrite_default_values(self, self.original_parse_args(args)) - restore_original_configuration(self) + prepare_to_read_cmd_args(self) + overwrite_default_values(self, self.original_parse_args(args)) + restore_original_configuration(self) diff --git a/gooey/python_bindings/config_generator.py b/gooey/python_bindings/config_generator.py index 394ad43b..031adc5f 100644 --- a/gooey/python_bindings/config_generator.py +++ b/gooey/python_bindings/config_generator.py @@ -11,50 +11,49 @@ default_layout = { 'widgets': [{ - 'type': 'CommandField', - 'required': True, - 'data': { - 'display_name': 'Enter Commands', - 'help': 'Enter command line arguments', - 'nargs': '', - 'commands': '', - 'choices': [], - 'default': None, - } + 'type': 'CommandField', + 'required': True, + 'data': { + 'display_name': 'Enter Commands', + 'help': 'Enter command line arguments', + 'nargs': '', + 'commands': '', + 'choices': [], + 'default': None, + } }], } # TODO: deprecate me -def create_from_parser(parser, source_path, **kwargs): - run_cmd = kwargs.get('target') - if run_cmd is None: - if hasattr(sys, 'frozen'): - run_cmd = quote(source_path) - else: - run_cmd = '{} -u {}'.format(quote(sys.executable), quote(source_path)) - build_spec = {**kwargs, 'target': run_cmd} +def create_from_parser(parser, source_path, **kwargs): + + run_cmd = kwargs.get('target') + if run_cmd is None: + if hasattr(sys, 'frozen'): + run_cmd = quote(source_path) + else: + run_cmd = '{} -u {}'.format(quote(sys.executable), + quote(source_path)) - if build_spec['monospace_display']: - warnings.warn('Gooey Option `monospace_display` is a legacy option.\n' - 'See the terminal_font_x options for more flexible control ' - 'over Gooey\'s text formatting') + build_spec = {**kwargs, 'target': run_cmd} + if build_spec['monospace_display']: + warnings.warn('Gooey Option `monospace_display` is a legacy option.\n' + 'See the terminal_font_x options for more flexible control ' + 'over Gooey\'s text formatting') - build_spec['program_description'] = build_spec['program_description'] or parser.description or '' + build_spec['program_description'] = build_spec['program_description'] or parser.description or '' - layout_data = (argparse_to_json.convert(parser, **build_spec) + layout_data = (argparse_to_json.convert(parser, **build_spec) if build_spec['advanced'] else default_layout.items()) - build_spec.update(layout_data) - - if len(build_spec['widgets']) > 1: - # there are subparsers involved - build_spec['show_sidebar'] = True - - return build_spec - + build_spec.update(layout_data) + if len(build_spec['widgets']) > 1: + # there are subparsers involved + build_spec['show_sidebar'] = True + return build_spec diff --git a/gooey/python_bindings/constants.py b/gooey/python_bindings/constants.py index 92d9f5b6..fa559432 100644 --- a/gooey/python_bindings/constants.py +++ b/gooey/python_bindings/constants.py @@ -25,4 +25,3 @@ # VALIDATE_FORM = 'VALIDATE_FORM' # ON_SUCCESS = 'ON_SUCCESS' # ON_ERROR = 'ON_ERROR' - diff --git a/gooey/python_bindings/constraints.py b/gooey/python_bindings/constraints.py index 20de5d6d..c7af62bd 100644 --- a/gooey/python_bindings/constraints.py +++ b/gooey/python_bindings/constraints.py @@ -28,14 +28,14 @@ def assert_visibility_requirements(action, options): raise ValueError(dedent( ''' When using Gooey's hidden field functionality, you must either ' - + (a) provide a default value, or ' (b) provide a custom validator' - - Without one of those, your users will be unable to advance past - the configuration screen as they cannot interact with your - hidden field, and the default validator requires something to - be present for fields marked as `required`. + + Without one of those, your users will be unable to advance past + the configuration screen as they cannot interact with your + hidden field, and the default validator requires something to + be present for fields marked as `required`. ''' )) @@ -46,4 +46,3 @@ def assert_listbox_constraints(widget, **kwargs): 'Gooey\'s Listbox widget requires that nargs be specified.\n' 'Nargs must be set to either `*` or `+` (e.g. nargs="*")' ) - diff --git a/gooey/python_bindings/control.py b/gooey/python_bindings/control.py index 9717828a..0b89e707 100644 --- a/gooey/python_bindings/control.py +++ b/gooey/python_bindings/control.py @@ -74,7 +74,7 @@ def parse_args(self: ArgumentParser, args=None, namespace=None): try: exec_dir = os.path.dirname(sys.argv[0]) open_path = os.path.join(exec_dir, params['load_build_config']) # type: ignore - build_spec = json.load(open(open_path, "r")) + build_spec = json.load(open(open_path, "r", encoding='utf-8')) except Exception as e: print('Exception loading Build Config from {0}: {1}'.format(params['load_build_config'], e)) sys.exit(1) @@ -91,7 +91,7 @@ def parse_args(self: ArgumentParser, args=None, namespace=None): if params['dump_build_config']: config_path = os.path.join(os.path.dirname(sys.argv[0]), 'gooey_config.json') print('Writing Build Config to: {}'.format(config_path)) - with open(config_path, 'w') as f: + with open(config_path, 'w', encoding='utf-8') as f: f.write(json.dumps(build_spec, indent=2)) bootstrap.run(build_spec) return parse_args @@ -121,10 +121,10 @@ def parse_args(self: ArgumentParser, args=None, namespace=None): state = args.gooey_state next_state = merge_errors(state, collect_errors(patched_parser, error_registry, vars(args))) write(serialize_outbound(next_state)) - exit(0) + sys.exit(0) except Exception as e: write(e) - exit(1) + sys.exit(1) return parse_args @@ -160,11 +160,11 @@ def parse_args(self: ArgumentParser, args=None, namespace=None): else: next_state = getattr(self, 'on_gooey_error', noop)(args, form_state) # type: ignore write(serialize_outbound(next_state)) - exit(0) + sys.exit(0) except Exception as e: write(''.join(traceback.format_stack())) write(e) - exit(1) + sys.exit(1) return parse_args @@ -191,16 +191,12 @@ def choose_hander(params: GooeyParams, cliargs: List[str]): Dispatches to the appropriate handler based on values found in the CLI arguments """ - with open('tmp.txt', 'w') as f: + with open('tmp.txt', 'w', encoding="utf-8") as f: f.write(str(sys.argv)) if '--gooey-validate-form' in cliargs: return validate_form(params) - elif '--gooey-run-is-success' in cliargs or '--gooey-run-is-failure' in cliargs: + if '--gooey-run-is-success' in cliargs or '--gooey-run-is-failure' in cliargs: return handle_completed_run(params) - elif '--ignore-gooey' in cliargs: + if '--ignore-gooey' in cliargs: return bypass_gooey(params) - else: - return boostrap_gooey(params) - - - + return boostrap_gooey(params) diff --git a/gooey/python_bindings/dynamics.py b/gooey/python_bindings/dynamics.py index a7c591fd..18e9c3bb 100644 --- a/gooey/python_bindings/dynamics.py +++ b/gooey/python_bindings/dynamics.py @@ -276,4 +276,3 @@ def monkey_patch_for_form_validation(error_registry: Dict[str, Exception], parse # patch(parser, '_check_value', new_check_value) # parser._check_value = new_check_value.__get__(parser, ArgumentParser) return monkey_patch_check_value(parser, new_check_value) - diff --git a/gooey/python_bindings/gooey_decorator.py b/gooey/python_bindings/gooey_decorator.py index ec17a6b4..739a7b81 100644 --- a/gooey/python_bindings/gooey_decorator.py +++ b/gooey/python_bindings/gooey_decorator.py @@ -48,4 +48,3 @@ def thunk(func): return Gooey(func, **params) return inner if callable(f) else thunk - diff --git a/gooey/python_bindings/gooey_parser.py b/gooey/python_bindings/gooey_parser.py index 6b4bebed..f4ade8d7 100644 --- a/gooey/python_bindings/gooey_parser.py +++ b/gooey/python_bindings/gooey_parser.py @@ -4,7 +4,7 @@ class GooeySubParser(_SubParsersAction): def __init__(self, *args, **kwargs): - super(GooeySubParser, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # TODO: figure out how to correctly dispatch all of these @@ -14,14 +14,14 @@ def __init__(self, parser, widgets, options, *args, **kwargs): self.parser = parser self.widgets = widgets self.options = options - super(GooeyArgumentGroup, self).__init__(self.parser, *args, **kwargs) + super().__init__(self.parser, *args, **kwargs) def add_argument(self, *args, **kwargs): widget = kwargs.pop('widget', None) metavar = kwargs.pop('metavar', None) options = kwargs.pop('gooey_options', None) - action = super(GooeyArgumentGroup, self).add_argument(*args, **kwargs) + action = super().add_argument(*args, **kwargs) self.parser._actions[-1].metavar = metavar self.widgets[self.parser._actions[-1].dest] = widget self.options[self.parser._actions[-1].dest] = options @@ -48,14 +48,14 @@ def __init__(self, container, parser, widgets, options, *args, **kwargs): self.parser = parser self.widgets = widgets self.options = options - super(GooeyMutuallyExclusiveGroup, self).__init__(container, *args, **kwargs) + super().__init__(container, *args, **kwargs) def add_argument(self, *args, **kwargs): widget = kwargs.pop('widget', None) metavar = kwargs.pop('metavar', None) options = kwargs.pop('gooey_options', None) - super(GooeyMutuallyExclusiveGroup, self).add_argument(*args, **kwargs) + super().add_argument(*args, **kwargs) self.parser._actions[-1].metavar = metavar self.widgets[self.parser._actions[-1].dest] = widget self.options[self.parser._actions[-1].dest] = options @@ -64,7 +64,7 @@ def add_argument(self, *args, **kwargs): class MyArgumentParser(ArgumentParser): def __init__(self, **kwargs): self._errors = [] - super(MyArgumentParser, self).__init__(**kwargs) + super().__init__(**kwargs) def error(self, message): self._errors.append(message) @@ -94,12 +94,12 @@ def inner(*args, **kwargs): class ActionWrapper(cls): def __call__(self, p, namespace, values, option_string, **qkwargs): # print('hello from', options, namespace, values, option_string, qkwargs) - super(ActionWrapper, self).__call__(p, namespace, values, option_string, **qkwargs) + super().__call__(p, namespace, values, option_string, **qkwargs) return ActionWrapper(*args, **kwargs) return inner -class GooeyParser(object): +class GooeyParser(): def __init__(self, **kwargs): on_success = kwargs.pop('on_success', None) on_error = kwargs.pop('on_error', None) @@ -219,4 +219,3 @@ def __getattr__(self, item): def __setattr__(self, key, value): return setattr(self.parser, key, value) - diff --git a/gooey/python_bindings/parameters.py b/gooey/python_bindings/parameters.py index 83e9fb32..89d46958 100644 --- a/gooey/python_bindings/parameters.py +++ b/gooey/python_bindings/parameters.py @@ -148,5 +148,4 @@ def parse_events(events: List[str]) -> List[str]: f'nrecognized event(s) were passed to `use_events`: {unknown_events}\n' f'Must be one of {Events._fields}\n' f'Consider using the `Events` object: `from gooey import Events`') - else: - return events + return events diff --git a/gooey/python_bindings/parser_exceptions.py b/gooey/python_bindings/parser_exceptions.py index 1dccaa67..271e4dac 100644 --- a/gooey/python_bindings/parser_exceptions.py +++ b/gooey/python_bindings/parser_exceptions.py @@ -6,14 +6,14 @@ class ParserError(Exception): - """Thrown when the parser can't find argparse functions the client code""" - pass + """Thrown when the parser can't find argparse functions the client code""" + pass class ArgumentError(Exception): - """Thrown when the parser is supplied with an incorrect argument format""" - pass + """Thrown when the parser is supplied with an incorrect argument format""" + pass if __name__ == '__main__': - pass \ No newline at end of file + pass diff --git a/gooey/tests/__init__.py b/gooey/tests/__init__.py index 4868a4c6..af90536d 100644 --- a/gooey/tests/__init__.py +++ b/gooey/tests/__init__.py @@ -30,9 +30,9 @@ from gooey.tests import * ``` """ -import wx import locale import platform +import wx class TestApp(wx.App): """ @@ -75,4 +75,4 @@ def setUpModule(): def tearDownModule(): global app - app.Destroy() \ No newline at end of file + app.Destroy() diff --git a/gooey/tests/all_widgets.py b/gooey/tests/all_widgets.py index b8198380..c75424ad 100644 --- a/gooey/tests/all_widgets.py +++ b/gooey/tests/all_widgets.py @@ -47,6 +47,3 @@ parser.add_argument("--dirchooser", default="dc-value", widget='DirChooser') parser.add_argument("--datechooser", default="2015-01-01", widget='DateChooser') parser.add_argument("--colourchooser", default="#000000", widget='ColourChooser') - - - diff --git a/gooey/tests/auto_start.py b/gooey/tests/auto_start.py index a5cad3e5..729f454a 100644 --- a/gooey/tests/auto_start.py +++ b/gooey/tests/auto_start.py @@ -1,8 +1,9 @@ import sys +from argparse import ArgumentParser from gooey import Gooey from gooey import GooeyParser -from argparse import ArgumentParser + @Gooey( progress_regex=r"^progress: (-?\d+)%$", diff --git a/gooey/tests/dynamics/files/basic.py b/gooey/tests/dynamics/files/basic.py index 75474eb5..80843a1d 100644 --- a/gooey/tests/dynamics/files/basic.py +++ b/gooey/tests/dynamics/files/basic.py @@ -3,7 +3,7 @@ from gooey import Events, Gooey -with open('tmp.txt', 'w') as f: +with open('tmp.txt', 'w', encoding='utf-8') as f: import sys f.write(str(sys.argv)) @@ -21,4 +21,3 @@ def main(): if __name__ == '__main__': main() - diff --git a/gooey/tests/dynamics/files/lifecycles.py b/gooey/tests/dynamics/files/lifecycles.py index 6b65e9c2..0040e5b0 100644 --- a/gooey/tests/dynamics/files/lifecycles.py +++ b/gooey/tests/dynamics/files/lifecycles.py @@ -4,7 +4,7 @@ from gooey import types as t -with open('tmp.txt', 'w') as f: +with open('tmp.txt', 'w', encoding='utf-8') as f: import sys f.write(str(sys.argv)) @@ -38,4 +38,3 @@ def main(): if __name__ == '__main__': main() - diff --git a/gooey/tests/dynamics/test_dynamics.py b/gooey/tests/dynamics/test_dynamics.py index 37bcea2f..fe16aca0 100644 --- a/gooey/tests/dynamics/test_dynamics.py +++ b/gooey/tests/dynamics/test_dynamics.py @@ -66,4 +66,3 @@ def test_patch_argument(self): assert parser.parse_args('a a1 --level-2 some-value --some-flag'.split()) assert parser.parse_args('b b1 --level-2 some-value --some-flag'.split()) assert not mock.called - diff --git a/gooey/tests/dynamics/test_live_updates.py b/gooey/tests/dynamics/test_live_updates.py index 36248815..075a987a 100644 --- a/gooey/tests/dynamics/test_live_updates.py +++ b/gooey/tests/dynamics/test_live_updates.py @@ -98,4 +98,3 @@ def test_lifecycle_handlers(self): textfield = gapp.getActiveFormState()[0] print(case['expected_update'], textfield['value']) self.assertEqual(case['expected_update'], textfield['value']) - diff --git a/gooey/tests/harness.py b/gooey/tests/harness.py index 36553ad2..a4dba43d 100644 --- a/gooey/tests/harness.py +++ b/gooey/tests/harness.py @@ -22,7 +22,7 @@ def instrumentGooey(parser, **kwargs) -> Tuple[wx.App, wx.Frame, RGooey]: Weirdness warning: this uses a globally reused wx.App instance. """ from gooey.tests import app - if app == None: + if app is None: raise Exception("App instance has not been created! This is likely due to " "you forgetting to add the magical import which makes all these " "tests work. See the module doc in gooey.tests.__init__ for guidance") diff --git a/gooey/tests/integration/__init__.py b/gooey/tests/integration/__init__.py index ff524384..9e8fc910 100644 --- a/gooey/tests/integration/__init__.py +++ b/gooey/tests/integration/__init__.py @@ -4,4 +4,4 @@ WX Python needs to control the main thread. So, in order to simulate a user running through the system, we have to execute the actual assertions in a different thread -""" \ No newline at end of file +""" diff --git a/gooey/tests/integration/integ_autostart.py b/gooey/tests/integration/integ_autostart.py index 5fbb3395..f17e9418 100644 --- a/gooey/tests/integration/integ_autostart.py +++ b/gooey/tests/integration/integ_autostart.py @@ -1,8 +1,9 @@ import time import unittest -from gooey.gui.lang.i18n import _ from tests.integration.programs import auto_start as auto_start_module +from gooey.gui.lang.i18n import _ + class TestGooeyIntegration(unittest.TestCase): @@ -60,9 +61,3 @@ def verifyAutoStart(self, app, buildSpec): if __name__ == '__main__': unittest.main() - - - - - - diff --git a/gooey/tests/integration/integ_subparser_demo.py b/gooey/tests/integration/integ_subparser_demo.py index b78bf024..7915010f 100644 --- a/gooey/tests/integration/integ_subparser_demo.py +++ b/gooey/tests/integration/integ_subparser_demo.py @@ -1,10 +1,11 @@ -import wx import time import unittest +import wx -from gooey.gui.lang.i18n import _ from tests.integration.programs import \ all_widgets_subparser as all_widgets_subparser_module +from gooey.gui.lang.i18n import _ + class TestGooeyIntegration11(unittest.TestCase): @@ -54,9 +55,3 @@ def gooeySanityTest(self, app, buildSpec): if __name__ == '__main__': unittest.main() - - - - - - diff --git a/gooey/tests/integration/integ_validations.py b/gooey/tests/integration/integ_validations.py index f20721c3..1568ee00 100644 --- a/gooey/tests/integration/integ_validations.py +++ b/gooey/tests/integration/integ_validations.py @@ -40,9 +40,3 @@ def verifyValidators(self, app, buildSpec): if __name__ == '__main__': unittest.main() - - - - - - diff --git a/gooey/tests/integration/integ_widget_demo.py b/gooey/tests/integration/integ_widget_demo.py index 70332133..187abfc7 100644 --- a/gooey/tests/integration/integ_widget_demo.py +++ b/gooey/tests/integration/integ_widget_demo.py @@ -2,8 +2,9 @@ import unittest import wx -from gooey.gui.lang.i18n import _ from tests.integration.programs import all_widgets as all_widgets_module +from gooey.gui.lang.i18n import _ + class TestGooeyIntegration99(unittest.TestCase): @@ -56,9 +57,3 @@ def gooeySanityTest(self, app, buildSpec): if __name__ == '__main__': unittest.main() - - - - - - diff --git a/gooey/tests/integration/programs/auto_start.py b/gooey/tests/integration/programs/auto_start.py index d1cd18aa..f3995a5e 100644 --- a/gooey/tests/integration/programs/auto_start.py +++ b/gooey/tests/integration/programs/auto_start.py @@ -1,8 +1,9 @@ import sys +from argparse import ArgumentParser from gooey import Gooey from gooey import GooeyParser -from argparse import ArgumentParser + @Gooey( progress_regex=r"^progress: (-?\d+)%$", diff --git a/gooey/tests/integration/programs/validations.py b/gooey/tests/integration/programs/validations.py index 5c1799fb..549ca9d4 100644 --- a/gooey/tests/integration/programs/validations.py +++ b/gooey/tests/integration/programs/validations.py @@ -30,4 +30,4 @@ def get_parser(): if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/gooey/tests/integration/runner.py b/gooey/tests/integration/runner.py index 63d03252..b2e2757a 100644 --- a/gooey/tests/integration/runner.py +++ b/gooey/tests/integration/runner.py @@ -42,5 +42,3 @@ def run_integration(module, assertionFunction, **kwargs): # any waiting it may be doing. testResult.result() del app - - diff --git a/gooey/tests/processor/files/ignore_break.py b/gooey/tests/processor/files/ignore_break.py index f18457dd..e3cc3502 100644 --- a/gooey/tests/processor/files/ignore_break.py +++ b/gooey/tests/processor/files/ignore_break.py @@ -17,4 +17,4 @@ def ignored_it(*args): while True: print(time.time()) - time.sleep(0.1) \ No newline at end of file + time.sleep(0.1) diff --git a/gooey/tests/processor/files/infinite_loop.py b/gooey/tests/processor/files/infinite_loop.py index 8ba82043..81cce199 100644 --- a/gooey/tests/processor/files/infinite_loop.py +++ b/gooey/tests/processor/files/infinite_loop.py @@ -15,4 +15,4 @@ while True: print(time.time()) - time.sleep(0.1) \ No newline at end of file + time.sleep(0.1) diff --git a/gooey/tests/processor/test_processor.py b/gooey/tests/processor/test_processor.py index eb6f4bf3..0d6adbf3 100644 --- a/gooey/tests/processor/test_processor.py +++ b/gooey/tests/processor/test_processor.py @@ -122,4 +122,3 @@ def test_ignore_sigint_family_signals(self): # but indeed ignored. It continued running and writing to stdout after # receiving the signal self.assertTrue(output.index("INTERRUPT") < len(output)) - diff --git a/gooey/tests/test_application.py b/gooey/tests/test_application.py index c6bcc4bb..64eb097a 100644 --- a/gooey/tests/test_application.py +++ b/gooey/tests/test_application.py @@ -124,4 +124,4 @@ def basicParser(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_argparse_to_json.py b/gooey/tests/test_argparse_to_json.py index 2505a27c..4ff1c9f2 100644 --- a/gooey/tests/test_argparse_to_json.py +++ b/gooey/tests/test_argparse_to_json.py @@ -3,12 +3,14 @@ import unittest from argparse import ArgumentParser, FileType +from gui.components.options.options import FileChooser +from gui.components.widgets import FileSaver + from gooey import GooeyParser from gooey.python_bindings import argparse_to_json from gooey.util.functional import getin from gooey.tests import * -from gui.components.options.options import FileChooser -from gui.components.widgets import FileSaver + class TestArgparse(unittest.TestCase): @@ -87,7 +89,7 @@ def test_choice_string_cooersion_no_default(self): choice_action = parser._actions[-1] result = argparse_to_json.action_to_json(choice_action, 'Dropdown', {}) self.assertEqual(getin(result, ['data', 'default']), None) - + def test_listbox_defaults_cast_correctly(self): """ @@ -289,4 +291,3 @@ def test_filetype_chooses_good_widget(self): action = [parser._actions[-1]] result = next(argparse_to_json.categorize(action, {}, {})) self.assertEqual(result['type'], expected_widget) - diff --git a/gooey/tests/test_checkbox.py b/gooey/tests/test_checkbox.py index 0b780d26..b5b16418 100644 --- a/gooey/tests/test_checkbox.py +++ b/gooey/tests/test_checkbox.py @@ -55,4 +55,4 @@ def testInitialValue(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_cli.py b/gooey/tests/test_cli.py index 85f540f8..14105ff2 100644 --- a/gooey/tests/test_cli.py +++ b/gooey/tests/test_cli.py @@ -18,4 +18,4 @@ def test_cli(self): {'clitype': 'optional', 'cmd': '-b 2', 'required': False}, ] - # print(cli.formValidationCmd('target', 'cmd', positionals, optionals)) \ No newline at end of file + # print(cli.formValidationCmd('target', 'cmd', positionals, optionals)) diff --git a/gooey/tests/test_cmd_args.py b/gooey/tests/test_cmd_args.py index 70a74a02..86d0775e 100644 --- a/gooey/tests/test_cmd_args.py +++ b/gooey/tests/test_cmd_args.py @@ -1,8 +1,8 @@ import unittest +from argparse import ArgumentParser from gooey import GooeyParser from gooey.python_bindings import cmd_args -from argparse import ArgumentParser from gooey.tests import * diff --git a/gooey/tests/test_config_generator.py b/gooey/tests/test_config_generator.py index 09258d04..34940698 100644 --- a/gooey/tests/test_config_generator.py +++ b/gooey/tests/test_config_generator.py @@ -57,4 +57,4 @@ def test_invalid_font_weights_throw_error(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_constraints.py b/gooey/tests/test_constraints.py index 5654156c..3fcbfe6e 100644 --- a/gooey/tests/test_constraints.py +++ b/gooey/tests/test_constraints.py @@ -95,4 +95,4 @@ def test_visibility_constraint(self): gooey_options={ 'visible': False, 'validator': {'test': 'true'} - }) \ No newline at end of file + }) diff --git a/gooey/tests/test_control.py b/gooey/tests/test_control.py index 5345dbd1..bac4b34c 100644 --- a/gooey/tests/test_control.py +++ b/gooey/tests/test_control.py @@ -11,25 +11,22 @@ from wx._core import CommandEvent -from gooey import GooeyParser from python_bindings.coms import decode_payload, deserialize_inbound from python_bindings.dynamics import patch_argument, check_value +from python_bindings.types import FormField +from tests.harness import instrumentGooey +from gooey.tests import * from gooey.python_bindings import control +from gooey import GooeyParser from gooey.python_bindings.parameters import gooey_params from gooey.gui import state as s from gooey.python_bindings.schema import validate_public_state -from python_bindings.types import FormField - -from tests.harness import instrumentGooey - -from gooey.tests import * def custom_type(x): if x == '1234': return x - else: - raise Exception('KABOOM!') + raise Exception('KABOOM!') class TestControl(unittest.TestCase): @@ -230,6 +227,3 @@ def test_ignore_gooey(self): def get_by_id(items: List[FormField], id: str): return [x for x in items if x['id'] == id][0] - - - diff --git a/gooey/tests/test_counter.py b/gooey/tests/test_counter.py index 10ef7236..af697b56 100644 --- a/gooey/tests/test_counter.py +++ b/gooey/tests/test_counter.py @@ -48,4 +48,4 @@ def testInitialValue(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_decoration.py b/gooey/tests/test_decoration.py index de2cb03c..060323bf 100644 --- a/gooey/tests/test_decoration.py +++ b/gooey/tests/test_decoration.py @@ -52,4 +52,4 @@ # # def test_thing(self, **kwargs): # print(main(1, 2)) -# print(help(main)) \ No newline at end of file +# print(help(main)) diff --git a/gooey/tests/test_dropdown.py b/gooey/tests/test_dropdown.py index 8c3c84d0..10f74b21 100644 --- a/gooey/tests/test_dropdown.py +++ b/gooey/tests/test_dropdown.py @@ -2,9 +2,10 @@ from argparse import ArgumentParser from unittest.mock import patch -from gooey import GooeyParser from tests.harness import instrumentGooey from gooey.tests import * +from gooey import GooeyParser + class TestGooeyDropdown(unittest.TestCase): @@ -89,4 +90,4 @@ def testInitialValue(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_filtering.py b/gooey/tests/test_filtering.py index 892fb221..4ae7efe2 100644 --- a/gooey/tests/test_filtering.py +++ b/gooey/tests/test_filtering.py @@ -1,8 +1,8 @@ import unittest -from gooey import PrefixTokenizers -from gui.components.filtering.prefix_filter import SearchOptions, PrefixSearch from collections import namedtuple +from gui.components.filtering.prefix_filter import SearchOptions, PrefixSearch +from gooey import PrefixTokenizers TestData = namedtuple('TestData', [ 'options', @@ -88,5 +88,3 @@ def test_prefix_searching(self): searcher = PrefixSearch(self.testdata, case.options) result = searcher.findMatches(case.input_string) self.assertEqual(result, case.expected_results) - - diff --git a/gooey/tests/test_header.py b/gooey/tests/test_header.py index ae0be0d7..6cec5cb6 100644 --- a/gooey/tests/test_header.py +++ b/gooey/tests/test_header.py @@ -63,4 +63,4 @@ def powerset(iterable): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_listbox.py b/gooey/tests/test_listbox.py index 79b64085..16faa471 100644 --- a/gooey/tests/test_listbox.py +++ b/gooey/tests/test_listbox.py @@ -55,4 +55,4 @@ def testInitialValue(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_numeric_inputs.py b/gooey/tests/test_numeric_inputs.py index e24edc44..c1765729 100644 --- a/gooey/tests/test_numeric_inputs.py +++ b/gooey/tests/test_numeric_inputs.py @@ -68,7 +68,7 @@ def testGooeyOptions(self): {'widget': 'DecimalField', 'gooey_options': {'min': 1234, 'max': 3456, 'increment': 2.2}}, {'widget': 'IntegerField', 'gooey_options': {'min': -100, 'max': 1234}}, {'widget': 'IntegerField', 'gooey_options': {'min': 1234, 'max': 3456}} - ]; + ] using = { 'min': lambda widget: widget.GetMin(), 'max': lambda widget: widget.GetMax(), @@ -108,4 +108,4 @@ def testNoLossOfPrecision(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_options.py b/gooey/tests/test_options.py index 5438093f..18068154 100644 --- a/gooey/tests/test_options.py +++ b/gooey/tests/test_options.py @@ -51,4 +51,4 @@ def test_only_provided_arguments_included(self): self.assertIn('label_color', option) option = options.TextField() - self.assertNotIn('label_color', option) \ No newline at end of file + self.assertNotIn('label_color', option) diff --git a/gooey/tests/test_parent_inheritance.py b/gooey/tests/test_parent_inheritance.py index a8b34ada..287858f2 100644 --- a/gooey/tests/test_parent_inheritance.py +++ b/gooey/tests/test_parent_inheritance.py @@ -83,4 +83,4 @@ def _verify_duplicate_parameters(self, action1, action2, parser): found += 1 self.assertEqual(2, found, "Expected a both actions handling a_file but got " + str(found)) self.assertEqual(parser.get_default("a_file"), "a") - self.assertNotEqual(action1, action2) \ No newline at end of file + self.assertNotEqual(action1, action2) diff --git a/gooey/tests/test_password.py b/gooey/tests/test_password.py index 4487141a..efafe8ab 100644 --- a/gooey/tests/test_password.py +++ b/gooey/tests/test_password.py @@ -29,4 +29,4 @@ def testPlaceholder(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_radiogroup.py b/gooey/tests/test_radiogroup.py index 37aa7a3a..894b131c 100644 --- a/gooey/tests/test_radiogroup.py +++ b/gooey/tests/test_radiogroup.py @@ -1,8 +1,8 @@ import unittest +from tests.harness import instrumentGooey from gooey import GooeyParser from gooey.tests import * -from tests.harness import instrumentGooey class TestRadioGroupBehavior(unittest.TestCase): @@ -186,4 +186,4 @@ def click_scenarios_initial_selection(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_slider.py b/gooey/tests/test_slider.py index 94557c90..41f83305 100644 --- a/gooey/tests/test_slider.py +++ b/gooey/tests/test_slider.py @@ -61,4 +61,4 @@ def testZerosAreReturned(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_textarea.py b/gooey/tests/test_textarea.py index 8d56e6a6..951060c7 100644 --- a/gooey/tests/test_textarea.py +++ b/gooey/tests/test_textarea.py @@ -29,4 +29,4 @@ def testPlaceholder(self): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_textfield.py b/gooey/tests/test_textfield.py index 1dc35759..eed3a004 100644 --- a/gooey/tests/test_textfield.py +++ b/gooey/tests/test_textfield.py @@ -58,4 +58,4 @@ def testDefaultAndInitialValue(self): self.assertEqual(widget.getValue()['cmd'], case.expectedAfterClearing) if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_time_remaining.py b/gooey/tests/test_time_remaining.py index fe67e29e..f7fdae3a 100644 --- a/gooey/tests/test_time_remaining.py +++ b/gooey/tests/test_time_remaining.py @@ -2,10 +2,11 @@ import unittest from argparse import ArgumentParser from itertools import * -from gooey.gui import state as s + from tests.harness import instrumentGooey +from gooey.gui import state as s from gooey.tests import * from gooey.util.functional import identity @@ -68,4 +69,4 @@ def powerset(iterable): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/gooey/tests/test_util.py b/gooey/tests/test_util.py index 469439db..7c3a19f0 100644 --- a/gooey/tests/test_util.py +++ b/gooey/tests/test_util.py @@ -24,7 +24,7 @@ def test_current_time(self): _start_time = get_current_time() self.assertGreater(_start_time,0) - + def test_format_interval(self): # Test same as TQDM https://github.com/tqdm/tqdm/blob/0cd9448b2bc08125e74538a2aea6af42ee1a7b6f/tqdm/tests/tests_tqdm.py#L234 # but in unittest form diff --git a/gooey/tests/tmmmmp.py b/gooey/tests/tmmmmp.py index 249acfe1..da45ad4f 100644 --- a/gooey/tests/tmmmmp.py +++ b/gooey/tests/tmmmmp.py @@ -17,4 +17,4 @@ def main(): parser.parse_args(['foo']) -main() \ No newline at end of file +main() diff --git a/gooey/util/functional.py b/gooey/util/functional.py index c0b53efd..4652be4d 100644 --- a/gooey/util/functional.py +++ b/gooey/util/functional.py @@ -3,7 +3,7 @@ """ from functools import reduce, wraps from copy import deepcopy -from itertools import chain, dropwhile +from itertools import chain from typing import Tuple, Any, List, Union from gooey.python_bindings.types import Try, Success, Failure @@ -46,8 +46,7 @@ def apply(_m, change: Tuple[Union[str, List[str]], Any]): path, value = change if isinstance(path, list): return associn(_m, path, value) - else: - return associn(_m, path.split('.'), value) + return associn(_m, path.split('.'), value) return reduce(apply, args, m) @@ -82,8 +81,7 @@ def compact(coll): """Returns a new list with all falsy values removed""" if isinstance(coll, dict): return {k:v for k,v in coll.items() if v is not None} - else: - return list(filter(None, coll)) + return list(filter(None, coll)) def ifPresent(f): @@ -91,8 +89,7 @@ def ifPresent(f): def inner(value): if value: return f(value) - else: - return True + return True return inner @@ -117,4 +114,3 @@ def inner(x) -> Try: except Exception as e: return Failure(e) return inner - diff --git a/setup.py b/setup.py index e2d82e68..38bcfbb2 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from setuptools import setup, find_packages -with open('README.md') as readme: +with open('README.md', encoding="utf-8") as readme: long_description = readme.read() version = '1.2.0-ALPHA' diff --git a/tmp.txt b/tmp.txt new file mode 100644 index 00000000..b118f773 --- /dev/null +++ b/tmp.txt @@ -0,0 +1 @@ +['c:\\Users\\markm\\.vscode\\extensions\\ms-python.python-2022.16.0\\pythonFiles\\visualstudio_py_testlauncher.py', '--us=./gooey', '--up=test*.py', '--uvInt=2', '--result-port=25179', '-ttests.dynamics.test_live_updates.TestLiveDynamicUpdates.test_lifecycle_handlers', '-ttests.dynamics.test_live_updates.TestLiveDynamicUpdates.test_validate_form', '-ttests.dynamics.test_live_updates.TestLiveDynamicUpdates.test_validate_form_without_errors', '--testFile=c:\\Users\\markm\\GitHub\\Gooey\\gooey\\tests\\dynamics\\test_live_updates.py'] \ No newline at end of file