From eb389c862ee11262e1c412eb50e7270a1df8777e Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Thu, 22 Jun 2023 10:21:42 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- NodeGraphQt/base/commands.py | 10 +- NodeGraphQt/base/factory.py | 11 +- NodeGraphQt/base/graph.py | 120 ++++++++---------- NodeGraphQt/base/menu.py | 17 +-- NodeGraphQt/base/model.py | 40 +++--- NodeGraphQt/base/node.py | 9 +- NodeGraphQt/base/port.py | 26 ++-- NodeGraphQt/custom_widgets/nodes_palette.py | 10 +- NodeGraphQt/custom_widgets/nodes_tree.py | 8 +- .../custom_widget_color_picker.py | 8 +- .../custom_widget_file_paths.py | 6 +- .../custom_widget_value_edit.py | 16 +-- .../properties_bin/custom_widget_vectors.py | 3 +- .../properties_bin/node_property_widgets.py | 21 +-- .../properties_bin/prop_widgets_abstract.py | 3 +- .../properties_bin/prop_widgets_base.py | 21 +-- NodeGraphQt/nodes/backdrop_node.py | 8 +- NodeGraphQt/nodes/base_node.py | 36 ++---- NodeGraphQt/nodes/group_node.py | 17 +-- NodeGraphQt/nodes/port_node.py | 12 +- NodeGraphQt/qgraphics/node_abstract.py | 7 +- NodeGraphQt/qgraphics/node_backdrop.py | 14 +- NodeGraphQt/qgraphics/node_base.py | 50 +++----- NodeGraphQt/qgraphics/node_circle.py | 28 ++-- NodeGraphQt/qgraphics/node_group.py | 16 +-- NodeGraphQt/qgraphics/node_port_in.py | 2 +- NodeGraphQt/qgraphics/node_port_out.py | 2 +- NodeGraphQt/qgraphics/pipe.py | 34 ++--- NodeGraphQt/qgraphics/port.py | 16 +-- NodeGraphQt/widgets/actions.py | 4 +- NodeGraphQt/widgets/dialogs.py | 8 +- NodeGraphQt/widgets/node_graph.py | 4 +- NodeGraphQt/widgets/node_widgets.py | 20 ++- NodeGraphQt/widgets/scene.py | 8 +- NodeGraphQt/widgets/tab_search.py | 18 ++- NodeGraphQt/widgets/viewer.py | 16 +-- NodeGraphQt/widgets/viewer_nav.py | 2 +- docs/_themes/sphinx_rtd_theme/__init__.py | 3 +- docs/conf.py | 4 +- examples/hotkeys/hotkey_functions.py | 14 +- 40 files changed, 251 insertions(+), 421 deletions(-) diff --git a/NodeGraphQt/base/commands.py b/NodeGraphQt/base/commands.py index 360150d5..4e7be492 100644 --- a/NodeGraphQt/base/commands.py +++ b/NodeGraphQt/base/commands.py @@ -16,7 +16,7 @@ class PropertyChangedCmd(QtWidgets.QUndoCommand): def __init__(self, node, name, value): QtWidgets.QUndoCommand.__init__(self) - self.setText('property "{}:{}"'.format(node.name(), name)) + self.setText(f'property "{node.name()}:{name}"') self.node = node self.name = name self.old_val = node.get_property(name) @@ -344,7 +344,7 @@ class PortLockedCmd(QtWidgets.QUndoCommand): def __init__(self, port): QtWidgets.QUndoCommand.__init__(self) - self.setText('lock port "{}"'.format(port.name())) + self.setText(f'lock port "{port.name()}"') self.port = port def undo(self): @@ -366,7 +366,7 @@ class PortUnlockedCmd(QtWidgets.QUndoCommand): def __init__(self, port): QtWidgets.QUndoCommand.__init__(self) - self.setText('unlock port "{}"'.format(port.name())) + self.setText(f'unlock port "{port.name()}"') self.port = port def undo(self): @@ -391,9 +391,9 @@ def __init__(self, port, visible): self.port = port self.visible = visible if visible: - self.setText('show port {}'.format(self.port.name())) + self.setText(f'show port {self.port.name()}') else: - self.setText('hide port {}'.format(self.port.name())) + self.setText(f'hide port {self.port.name()}') def set_visible(self, visible): self.port.model.visible = visible diff --git a/NodeGraphQt/base/factory.py b/NodeGraphQt/base/factory.py index ac209c75..a3ea018c 100644 --- a/NodeGraphQt/base/factory.py +++ b/NodeGraphQt/base/factory.py @@ -55,8 +55,7 @@ def create_node_instance(self, node_type=None): if node_type in self.aliases: node_type = self.aliases[node_type] - _NodeClass = self.__nodes.get(node_type) - if _NodeClass: + if _NodeClass := self.__nodes.get(node_type): return _NodeClass() def register_node(self, node, alias=None): @@ -75,9 +74,8 @@ def register_node(self, node, alias=None): if self.__nodes.get(node_type): raise NodeRegistrationError( - 'node type "{}" already registered to "{}"! ' - 'Please specify a new plugin class name or __identifier__.' - .format(node_type, self.__nodes[node_type])) + f'node type "{node_type}" already registered to "{self.__nodes[node_type]}"! Please specify a new plugin class name or __identifier__.' + ) self.__nodes[node_type] = node if self.__names.get(name): @@ -88,8 +86,7 @@ def register_node(self, node, alias=None): if alias: if self.__aliases.get(alias): raise NodeRegistrationError( - 'Alias: "{}" already registered to "{}"' - .format(alias, self.__aliases.get(alias)) + f'Alias: "{alias}" already registered to "{self.__aliases.get(alias)}"' ) self.__aliases[alias] = node_type diff --git a/NodeGraphQt/base/graph.py b/NodeGraphQt/base/graph.py index 6c4c8f65..b9b87bb5 100644 --- a/NodeGraphQt/base/graph.py +++ b/NodeGraphQt/base/graph.py @@ -178,8 +178,7 @@ def __init__(self, parent=None, **kwargs): self._wire_signals() def __repr__(self): - return '<{}("root") object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}("root") object at {hex(id(self))}>' def _register_context_menu(self): """ @@ -331,12 +330,11 @@ def _on_node_data_dropped(self, data, pos): data (QtCore.QMimeData): mime data. pos (QtCore.QPoint): scene position relative to the drop. """ - uri_regex = re.compile(r'{}(?:/*)([\w/]+)(\.\w+)'.format(URI_SCHEME)) - urn_regex = re.compile(r'{}([\w\.:;]+)'.format(URN_SCHEME)) + uri_regex = re.compile(f'{URI_SCHEME}(?:/*)([\w/]+)(\.\w+)') + urn_regex = re.compile(f'{URN_SCHEME}([\w\.:;]+)') if data.hasFormat('text/uri-list'): for url in data.urls(): - local_file = url.toLocalFile() - if local_file: + if local_file := url.toLocalFile(): try: self.import_session(local_file) continue @@ -347,11 +345,11 @@ def _on_node_data_dropped(self, data, pos): uri_search = uri_regex.search(url_str) urn_search = urn_regex.search(url_str) if uri_search: - path = uri_search.group(1) - ext = uri_search.group(2) - self.import_session('{}{}'.format(path, ext)) + path = uri_search[1] + ext = uri_search[2] + self.import_session(f'{path}{ext}') elif urn_search: - search_str = urn_search.group(1) + search_str = urn_search[1] node_ids = sorted(re.findall('node:([\w\\.]+)', search_str)) x, y = pos.x(), pos.y() for node_id in node_ids: @@ -481,8 +479,7 @@ def widget(self): # hide the close button on the first tab. tab_bar = self._widget.tabBar() for btn_flag in [tab_bar.RightSide, tab_bar.LeftSide]: - tab_btn = tab_bar.tabButton(0, btn_flag) - if tab_btn: + if tab_btn := tab_bar.tabButton(0, btn_flag): tab_btn.deleteLater() tab_bar.setTabButton(0, btn_flag, None) self._widget.tabCloseRequested.connect( @@ -842,7 +839,7 @@ def set_context_menu_from_file(self, file_path, menu=None): menu = menu or 'graph' if not os.path.isfile(file_path): - raise IOError('file doesn\'t exists: "{}"'.format(file_path)) + raise IOError(f"""file doesn\'t exists: "{file_path}\"""") with open(file_path) as f: data = json.load(f) @@ -1050,10 +1047,10 @@ def fit_to_selection(self): Sets the zoom level to fit selected nodes. If no nodes are selected then all nodes in the graph will be framed. """ - nodes = self.selected_nodes() or self.all_nodes() - if not nodes: + if nodes := self.selected_nodes() or self.all_nodes(): + self._viewer.zoom_to_nodes([n.view for n in nodes]) + else: return - self._viewer.zoom_to_nodes([n.view for n in nodes]) def reset_zoom(self): """ @@ -1309,7 +1306,7 @@ def add_node(self, node, pos=None, selected=True, push_undo=True): node.update() if push_undo: - self._undo_stack.beginMacro('add node: "{}"'.format(node.name())) + self._undo_stack.beginMacro(f'add node: "{node.name()}"') self._undo_stack.push(NodeAddedCmd(self, node, pos)) if selected: node.set_selected(True) @@ -1326,10 +1323,10 @@ def delete_node(self, node, push_undo=True): push_undo (bool): register the command to the undo stack. (default: True) """ assert isinstance(node, NodeObject), \ - 'node must be a instance of a NodeObject.' + 'node must be a instance of a NodeObject.' node_id = node.id if push_undo: - self._undo_stack.beginMacro('delete node: "{}"'.format(node.name())) + self._undo_stack.beginMacro(f'delete node: "{node.name()}"') if isinstance(node, BaseNode): for p in node.input_ports(): @@ -1372,7 +1369,7 @@ def remove_node(self, node, push_undo=True): assert isinstance(node, NodeObject), 'node must be a Node instance.' if push_undo: - self._undo_stack.beginMacro('delete node: "{}"'.format(node.name())) + self._undo_stack.beginMacro(f'delete node: "{node.name()}"') # collapse group node before removing. if isinstance(node, GroupNode) and node.is_expanded: @@ -1413,9 +1410,7 @@ def delete_nodes(self, nodes, push_undo=True): return node_ids = [n.id for n in nodes] if push_undo: - self._undo_stack.beginMacro( - 'deleted "{}" node(s)'.format(len(nodes)) - ) + self._undo_stack.beginMacro(f'deleted "{len(nodes)}" node(s)') for node in nodes: # collapse group node before removing. @@ -1461,25 +1456,24 @@ def extract_nodes(self, nodes, push_undo=True, prompt_warning=True): if not isinstance(node, BaseNode): continue - for port in node.input_ports() + node.output_ports(): - if port.locked(): - locked_ports.append('{0.node.name}: {0.name}'.format(port)) - + locked_ports.extend( + '{0.node.name}: {0.name}'.format(port) + for port in node.input_ports() + node.output_ports() + if port.locked() + ) base_nodes.append(node) if locked_ports: - message = ( - 'Selected nodes cannot be extracted because the following ' - 'ports are locked:\n{}'.format('\n'.join(sorted(locked_ports))) - ) if prompt_warning: + message = ( + 'Selected nodes cannot be extracted because the following ' + 'ports are locked:\n{}'.format('\n'.join(sorted(locked_ports))) + ) self._viewer.message_dialog(message, 'Can\'t Extract Nodes') return if push_undo: - self._undo_stack.beginMacro( - 'extracted "{}" node(s)'.format(len(nodes)) - ) + self._undo_stack.beginMacro(f'extracted "{len(nodes)}" node(s)') for node in base_nodes: for port in node.input_ports() + node.output_ports(): @@ -1507,11 +1501,7 @@ def selected_nodes(self): Returns: list[NodeGraphQt.BaseNode]: list of nodes. """ - nodes = [] - for item in self._viewer.selected_nodes(): - node = self._model.nodes[item.id] - nodes.append(node) - return nodes + return [self._model.nodes[item.id] for item in self._viewer.selected_nodes()] def select_all(self): """ @@ -1586,14 +1576,14 @@ def get_unique_name(self, name): search = regex.search(name) if not search: for x in range(1, len(node_names) + 2): - new_name = '{} {}'.format(name, x) + new_name = f'{name} {x}' if new_name not in node_names: return new_name - version = search.group(1) + version = search[1] name = name[:len(version) * -1].strip() for x in range(1, len(node_names) + 2): - new_name = '{} {}'.format(name, x) + new_name = f'{name} {x}' if new_name not in node_names: return new_name @@ -1655,7 +1645,7 @@ def _serialize(self, nodes): n.update_model() node_dict = n.model.to_dict - nodes_data.update(node_dict) + nodes_data |= node_dict for n_id, n_data in nodes_data.items(): serial_data['nodes'][n_id] = n_data @@ -1725,8 +1715,7 @@ def _deserialize(self, data, relative_pos=False, pos=None): nodes = {} for n_id, n_data in data.get('nodes', {}).items(): identifier = n_data['type_'] - node = self._node_factory.create_node_instance(identifier) - if node: + if node := self._node_factory.create_node_instance(identifier): node.NODE_NAME = n_data.get('name', node.NODE_NAME) # set properties. for prop in node.model.properties.keys(): @@ -1851,7 +1840,7 @@ def load_session(self, file_path): """ file_path = file_path.strip() if not os.path.isfile(file_path): - raise IOError('file does not exist: {}'.format(file_path)) + raise IOError(f'file does not exist: {file_path}') self.clear_session() self.import_session(file_path) @@ -1865,14 +1854,14 @@ def import_session(self, file_path): """ file_path = file_path.strip() if not os.path.isfile(file_path): - raise IOError('file does not exist: {}'.format(file_path)) + raise IOError(f'file does not exist: {file_path}') try: with open(file_path) as data_file: layout_data = json.load(data_file) except Exception as e: layout_data = None - print('Cannot read data from file.\n{}'.format(e)) + print(f'Cannot read data from file.\n{e}') if not layout_data: return @@ -1899,8 +1888,7 @@ def copy_nodes(self, nodes=None): return False clipboard = QtWidgets.QApplication.clipboard() serial_data = self._serialize(nodes) - serial_str = json.dumps(serial_data) - if serial_str: + if serial_str := json.dumps(serial_data): clipboard.setText(serial_str) return True return False @@ -1962,8 +1950,7 @@ def paste_nodes(self): try: serial_data = json.loads(cb_text) except json.decoder.JSONDecodeError as e: - print('ERROR: Can\'t Decode Clipboard Data:\n' - '"{}"'.format(cb_text)) + print(f"""ERROR: Can\'t Decode Clipboard Data:\n"{cb_text}\"""") return self._undo_stack.beginMacro('pasted nodes') @@ -2021,7 +2008,7 @@ def disable_nodes(self, nodes, mode=None): if mode is not None: states = {False: 'enable', True: 'disable'} - text = '{} ({}) nodes'.format(states[mode], len(nodes)) + text = f'{states[mode]} ({len(nodes)}) nodes' self._undo_stack.beginMacro(text) [n.set_disabled(mode) for n in nodes] self._undo_stack.endMacro() @@ -2031,9 +2018,9 @@ def disable_nodes(self, nodes, mode=None): enabled_count = len([n for n in nodes if n.disabled()]) disabled_count = len([n for n in nodes if not n.disabled()]) if enabled_count > 0: - text.append('enabled ({})'.format(enabled_count)) + text.append(f'enabled ({enabled_count})') if disabled_count > 0: - text.append('disabled ({})'.format(disabled_count)) + text.append(f'disabled ({disabled_count})') text = ' / '.join(text) + ' nodes' self._undo_stack.beginMacro(text) @@ -2070,10 +2057,7 @@ def _update_node_rank(node, nodes_rank, down_stream=True): rank = nodes_rank[node] + 1 for n in connected_nodes: - if n in nodes_rank: - nodes_rank[n] = max(nodes_rank[n], rank) - else: - nodes_rank[n] = rank + nodes_rank[n] = max(nodes_rank[n], rank) if n in nodes_rank else rank NodeGraph._update_node_rank(n, nodes_rank, down_stream) @staticmethod @@ -2153,7 +2137,7 @@ def auto_layout_nodes(self, nodes=None, down_stream=True, start_nodes=None): node_height = 120 for rank in sorted(range(len(rank_map)), reverse=not down_stream): ranked_nodes = rank_map[rank] - max_width = max([node.view.width for node in ranked_nodes]) + max_width = max(node.view.width for node in ranked_nodes) current_x += max_width current_y = 0 for idx, node in enumerate(ranked_nodes): @@ -2168,7 +2152,7 @@ def auto_layout_nodes(self, nodes=None, down_stream=True, start_nodes=None): node_width = 250 for rank in sorted(range(len(rank_map)), reverse=not down_stream): ranked_nodes = rank_map[rank] - max_height = max([node.view.height for node in ranked_nodes]) + max_height = max(node.view.height for node in ranked_nodes) current_y += max_height current_x = 0 for idx, node in enumerate(ranked_nodes): @@ -2371,7 +2355,7 @@ def collapse_group_node(self, node): return if node.id not in self._sub_graphs: - err = '{} sub graph not initialized!'.format(node.name()) + err = f'{node.name()} sub graph not initialized!' raise RuntimeError(err) sub_graph = self._sub_graphs.pop(node.id) @@ -2428,8 +2412,7 @@ def __init__(self, parent=None, node=None, node_factory=None, **kwargs): self._clone_context_menu_from_parent() def __repr__(self): - return '<{}("{}") object at {}>'.format( - self.__class__.__name__, self._node.name(), hex(id(self))) + return f'<{self.__class__.__name__}("{self._node.name()}") object at {hex(id(self))}>' def _register_builtin_nodes(self): """ @@ -2626,9 +2609,7 @@ def _on_navigation_changed(self, node_id, rm_node_ids): child_node = self.sub_graphs[rm_node_id].node self.collapse_group_node(child_node) - # show the selected node id sub graph. - sub_graph = self.sub_graphs.get(node_id) - if sub_graph: + if sub_graph := self.sub_graphs.get(node_id): self.widget.show_viewer(sub_graph.subviewer_widget) sub_graph.viewer().setFocus() @@ -2757,7 +2738,7 @@ def delete_node(self, node, push_undo=True): # note: port nodes can only be deleted by deleting the parent # port object. raise NodeDeletionError( - '{} can\'t be deleted as it is attached to a port!'.format(node) + f"{node} can\'t be deleted as it is attached to a port!" ) super(SubGraph, self).delete_node(node, push_undo=push_undo) @@ -2778,8 +2759,7 @@ def delete_nodes(self, nodes, push_undo=True): # note: port nodes can only be deleted by deleting the parent # port object. raise NodeDeletionError( - '{} can\'t be deleted as it is attached to a port!' - .format(node) + f"{node} can\'t be deleted as it is attached to a port!" ) super(SubGraph, self).delete_nodes(nodes, push_undo=push_undo) diff --git a/NodeGraphQt/base/menu.py b/NodeGraphQt/base/menu.py index d3a2f982..db0c1a1c 100644 --- a/NodeGraphQt/base/menu.py +++ b/NodeGraphQt/base/menu.py @@ -38,8 +38,7 @@ def __init__(self, graph, qmenu): self._items = [] def __repr__(self): - return '<{}("{}") object at {}>'.format( - self.__class__.__name__, self.name(), hex(id(self))) + return f'<{self.__class__.__name__}("{self.name()}") object at {hex(id(self))}>' @property def qmenu(self): @@ -104,7 +103,7 @@ def add_menu(self, name): NodeGraphQt.NodeGraphMenu: the appended menu item. """ if name in self._menus: - raise NodeMenuError('menu object "{}" already exists!'.format(name)) + raise NodeMenuError(f'menu object "{name}" already exists!') base_menu = BaseMenu(name, self.qmenu) self.qmenu.addMenu(base_menu) menu = NodeGraphMenu(self._graph, base_menu) @@ -130,14 +129,13 @@ def add_command(self, name, func=None, shortcut=None): action.setShortcutVisibleInContextMenu(True) if isinstance(shortcut, str): - search = re.search(r'(?:\.|)QKeySequence\.(\w+)', shortcut) - if search: - shortcut = getattr(QtGui.QKeySequence, search.group(1)) - elif all([i in ['Alt', 'Enter'] for i in shortcut.split('+')]): + if search := re.search(r'(?:\.|)QKeySequence\.(\w+)', shortcut): + shortcut = getattr(QtGui.QKeySequence, search[1]) + elif all(i in ['Alt', 'Enter'] for i in shortcut.split('+')): shortcut = QtGui.QKeySequence( QtCore.Qt.ALT + QtCore.Qt.Key_Return ) - elif all([i in ['Return', 'Enter'] for i in shortcut.split('+')]): + elif all(i in ['Return', 'Enter'] for i in shortcut.split('+')): shortcut = QtCore.Qt.Key_Return if shortcut: @@ -247,8 +245,7 @@ def __init__(self, graph, qaction, func=None): self._func = func def __repr__(self): - return '<{}("{}") object at {}>'.format( - self.__class__.__name__, self.name(), hex(id(self))) + return f'<{self.__class__.__name__}("{self.name()}") object at {hex(id(self))}>' @property def qaction(self): diff --git a/NodeGraphQt/base/model.py b/NodeGraphQt/base/model.py index 89bf5e67..d602b17a 100644 --- a/NodeGraphQt/base/model.py +++ b/NodeGraphQt/base/model.py @@ -26,8 +26,7 @@ def __init__(self, node): self.connected_ports = defaultdict(list) def __repr__(self): - return '<{}(\'{}\') object at {}>'.format( - self.__class__.__name__, self.name, hex(id(self))) + return f"<{self.__class__.__name__}(\'{self.name}\') object at {hex(id(self))}>" @property def to_dict(self): @@ -117,8 +116,7 @@ def __init__(self): self._TEMP_reject_connection_types = {} def __repr__(self): - return '<{}(\'{}\') object at {}>'.format( - self.__class__.__name__, self.name, self.id) + return f"<{self.__class__.__name__}(\'{self.name}\') object at {self.id}>" def add_property(self, name, value, items=None, range=None, widget_type=None, tab=None): @@ -138,11 +136,9 @@ def add_property(self, name, value, items=None, range=None, tab = tab or 'Properties' if name in self.properties.keys(): - raise NodePropertyError( - '"{}" reserved for default property.'.format(name)) + raise NodePropertyError(f'"{name}" reserved for default property.') if name in self._custom_prop.keys(): - raise NodePropertyError( - '"{}" property already exists.'.format(name)) + raise NodePropertyError(f'"{name}" property already exists.') self._custom_prop[name] = value @@ -179,7 +175,7 @@ def set_property(self, name, value): elif name in self._custom_prop.keys(): self._custom_prop[name] = value else: - raise NodePropertyError('No property "{}"'.format(name)) + raise NodePropertyError(f'No property "{name}"') def get_property(self, name): """ @@ -226,8 +222,7 @@ def get_tab_name(self, name): """ model = self._graph_model if model is None: - attrs = self._TEMP_property_attrs.get(name) - if attrs: + if attrs := self._TEMP_property_attrs.get(name): return attrs[name].get('tab') return return model.get_node_common_properties(self.type_)[name]['tab'] @@ -250,8 +245,7 @@ def add_port_accept_connection_type( accept_ptype (str): port type accept. accept_ntype (str):port node type to accept. """ - model = self._graph_model - if model: + if model := self._graph_model: model.add_port_accept_connection_type( port_name, port_type, node_type, accept_pname, accept_ptype, accept_ntype @@ -266,7 +260,7 @@ def add_port_accept_connection_type( connection_data = connection_data[key] if accept_ptype not in connection_data: - connection_data[accept_ptype] = set([accept_pname]) + connection_data[accept_ptype] = {accept_pname} else: connection_data[accept_ptype].add(accept_pname) @@ -291,8 +285,7 @@ def add_port_reject_connection_type( Returns: """ - model = self._graph_model - if model: + if model := self._graph_model: model.add_port_reject_connection_type( port_name, port_type, node_type, reject_pname, reject_ptype, reject_ntype @@ -307,7 +300,7 @@ def add_port_reject_connection_type( connection_data = connection_data[key] if reject_ptype not in connection_data: - connection_data[reject_ptype] = set([reject_pname]) + connection_data[reject_ptype] = {reject_pname} else: connection_data[reject_ptype].add(reject_pname) @@ -384,8 +377,7 @@ def to_dict(self): 'multi_connection': model.multi_connection, 'display_name': model.display_name, }) - connected_ports = model.to_dict['connected_ports'] - if connected_ports: + if connected_ports := model.to_dict['connected_ports']: inputs[name] = connected_ports for name, model in node_dict.pop('outputs').items(): if self.port_deletion_allowed: @@ -394,8 +386,7 @@ def to_dict(self): 'multi_connection': model.multi_connection, 'display_name': model.display_name, }) - connected_ports = model.to_dict['connected_ports'] - if connected_ports: + if connected_ports := model.to_dict['connected_ports']: outputs[name] = connected_ports if inputs: node_dict['inputs'] = inputs @@ -409,8 +400,7 @@ def to_dict(self): if self.subgraph_session: node_dict['subgraph_session'] = self.subgraph_session - custom_props = node_dict.pop('_custom_prop', {}) - if custom_props: + if custom_props := node_dict.pop('_custom_prop', {}): node_dict['custom'] = custom_props exclude = ['_graph_model', @@ -537,7 +527,7 @@ def add_port_accept_connection_type( connection_data = connection_data[key] if accept_ptype not in connection_data: - connection_data[accept_ptype] = set([accept_pname]) + connection_data[accept_ptype] = {accept_pname} else: connection_data[accept_ptype].add(accept_pname) @@ -582,7 +572,7 @@ def add_port_reject_connection_type( connection_data = connection_data[key] if reject_ptype not in connection_data: - connection_data[reject_ptype] = set([reject_pname]) + connection_data[reject_ptype] = {reject_pname} else: connection_data[reject_ptype].add(reject_pname) diff --git a/NodeGraphQt/base/node.py b/NodeGraphQt/base/node.py index 0a43a3c9..c14e148d 100644 --- a/NodeGraphQt/base/node.py +++ b/NodeGraphQt/base/node.py @@ -97,8 +97,7 @@ def __init__(self, qgraphics_item=None): self._view.layout_direction = self._model.layout_direction def __repr__(self): - return '<{}("{}") object at {}>'.format( - self.__class__.__name__, self.NODE_NAME, hex(id(self))) + return f'<{self.__class__.__name__}("{self.NODE_NAME}") object at {hex(id(self))}>' @_ClassProperty def type_(cls): @@ -109,7 +108,7 @@ def type_(cls): Returns: str: node type (``__identifier__.__className__``) """ - return cls.__identifier__ + '.' + cls.__name__ + return f'{cls.__identifier__}.{cls.__name__}' @property def id(self): @@ -405,9 +404,7 @@ def set_property(self, name, value, push_undo=True): if self.graph: undo_cmd = PropertyChangedCmd(self, name, value) if name == 'name': - undo_cmd.setText( - 'renamed "{}" to "{}"'.format(self.name(), value) - ) + undo_cmd.setText(f'renamed "{self.name()}" to "{value}"') if push_undo: undo_stack = self.graph.undo_stack() undo_stack.push(undo_cmd) diff --git a/NodeGraphQt/base/port.py b/NodeGraphQt/base/port.py index 9ff38d36..670c07b0 100644 --- a/NodeGraphQt/base/port.py +++ b/NodeGraphQt/base/port.py @@ -37,8 +37,7 @@ def __init__(self, node, port): def __repr__(self): port = str(self.__class__.__name__) - return '<{}("{}") object at {}>'.format( - port, self.name(), hex(id(self))) + return f'<{port}("{self.name()}") object at {hex(id(self))}>' @property def view(self): @@ -169,10 +168,7 @@ def set_locked(self, state=False, connected_ports=True, push_undo=True): """ graph = self.node().graph undo_stack = graph.undo_stack() - if state: - undo_cmd = PortLockedCmd(self) - else: - undo_cmd = PortUnlockedCmd(self) + undo_cmd = PortLockedCmd(self) if state else PortUnlockedCmd(self) if push_undo: undo_stack.push(undo_cmd) else: @@ -218,33 +214,28 @@ def connect_to(self, port=None, push_undo=True): if self.locked() or port.locked(): name = [p.name() for p in [self, port] if p.locked()][0] - raise PortError( - 'Can\'t connect port because "{}" is locked.'.format(name)) + raise PortError(f"""Can\'t connect port because "{name}" is locked.""") # validate accept connection. node_type = self.node().type_ - accepted_types = port.accepted_port_types().get(node_type) - if accepted_types: + if accepted_types := port.accepted_port_types().get(node_type): accepted_pnames = accepted_types.get(self.type_()) or set([]) if self.name() not in accepted_pnames: return node_type = port.node().type_ - accepted_types = self.accepted_port_types().get(node_type) - if accepted_types: + if accepted_types := self.accepted_port_types().get(node_type): accepted_pnames = accepted_types.get(port.type_()) or set([]) if port.name() not in accepted_pnames: return # validate reject connection. node_type = self.node().type_ - rejected_types = port.rejected_port_types().get(node_type) - if rejected_types: + if rejected_types := port.rejected_port_types().get(node_type): rejected_pnames = rejected_types.get(self.type_()) or set([]) if self.name() in rejected_pnames: return node_type = port.node().type_ - rejected_types = self.rejected_port_types().get(node_type) - if rejected_types: + if rejected_types := self.rejected_port_types().get(node_type): rejected_pnames = rejected_types.get(port.type_()) or set([]) if port.name() in rejected_pnames: return @@ -329,8 +320,7 @@ def disconnect_from(self, port=None, push_undo=True): if self.locked() or port.locked(): name = [p.name() for p in [self, port] if p.locked()][0] - raise PortError( - 'Can\'t disconnect port because "{}" is locked.'.format(name)) + raise PortError(f"""Can\'t disconnect port because "{name}" is locked.""") graph = self.node().graph if push_undo: diff --git a/NodeGraphQt/custom_widgets/nodes_palette.py b/NodeGraphQt/custom_widgets/nodes_palette.py index 91a94f28..afe01568 100644 --- a/NodeGraphQt/custom_widgets/nodes_palette.py +++ b/NodeGraphQt/custom_widgets/nodes_palette.py @@ -122,8 +122,7 @@ def __init__(self, parent=None): super(NodesGridProxyModel, self).__init__(parent) def mimeData(self, indexes): - node_ids = ['node:{}'.format(i.data(QtCore.Qt.ToolTipRole)) - for i in indexes] + node_ids = [f'node:{i.data(QtCore.Qt.ToolTipRole)}' for i in indexes] node_urn = URN_SCHEME + ';'.join(node_ids) mime_data = super(NodesGridProxyModel, self).mimeData(indexes) mime_data.setUrls([node_urn]) @@ -211,9 +210,7 @@ def __init__(self, parent=None, node_graph=None): node_graph.nodes_registered.connect(self._on_nodes_registered) def __repr__(self): - return '<{} object at {}>'.format( - self.__class__.__name__, hex(id(self)) - ) + return f'<{self.__class__.__name__} object at {hex(id(self))}>' def _on_nodes_registered(self, nodes): """ @@ -301,8 +298,7 @@ def set_category_label(self, category, label): """ if label in self._custom_labels.values(): labels = {v: k for k, v in self._custom_labels.items()} - raise ValueError('label "{}" already in use for "{}"' - .format(label, labels[label])) + raise ValueError(f'label "{label}" already in use for "{labels[label]}"') previous_label = self._custom_labels.get(category, '') for idx in range(self._tab_widget.count()): tab_text = self._tab_widget.tabText(idx) diff --git a/NodeGraphQt/custom_widgets/nodes_tree.py b/NodeGraphQt/custom_widgets/nodes_tree.py index 709e90a7..dd80a9aa 100644 --- a/NodeGraphQt/custom_widgets/nodes_tree.py +++ b/NodeGraphQt/custom_widgets/nodes_tree.py @@ -62,12 +62,10 @@ def __init__(self, parent=None, node_graph=None): self._build_tree() def __repr__(self): - return '<{} object at {}>'.format( - self.__class__.__name__, hex(id(self)) - ) + return f'<{self.__class__.__name__} object at {hex(id(self))}>' def mimeData(self, items): - node_ids = ['node:{}'.format(i.toolTip(0)) for i in items] + node_ids = [f'node:{i.toolTip(0)}' for i in items] node_urn = URN_SCHEME + ';'.join(node_ids) mime_data = super(NodesTreeWidget, self).mimeData(items) mime_data.setUrls([node_urn]) @@ -91,7 +89,7 @@ def _build_tree(self): if category in self._custom_labels.keys(): label = self._custom_labels[category] else: - label = '{}'.format(category) + label = f'{category}' cat_item = BaseNodeTreeItem(self, [label], type=TYPE_CATEGORY) cat_item.setFirstColumnSpanned(True) cat_item.setFlags(QtCore.Qt.ItemIsEnabled) diff --git a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_color_picker.py b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_color_picker.py index 79d0813b..20a5ff4a 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_color_picker.py +++ b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_color_picker.py @@ -49,9 +49,7 @@ def _update_color(self): QPushButton::hover {{background-color: rgba({0}, {1}, {2}, 200);}} '''.format(*c) ) - self._button.setToolTip( - 'rgb: {}\nhex: {}'.format(self._color[:3], hex_color) - ) + self._button.setToolTip(f'rgb: {self._color[:3]}\nhex: {hex_color}') def get_value(self): return self._color[:3] @@ -94,9 +92,7 @@ def _update_color(self): QPushButton::hover {{background-color: rgba({0}, {1}, {2}, {3});}} '''.format(*c) ) - self._button.setToolTip( - 'rgba: {}\nhex: {}'.format(self._color, hex_color) - ) + self._button.setToolTip(f'rgba: {self._color}\nhex: {hex_color}') def get_value(self): return self._color[:4] diff --git a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_file_paths.py b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_file_paths.py index 51b811ee..a248edea 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_file_paths.py +++ b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_file_paths.py @@ -35,8 +35,7 @@ def _on_select_file(self): file_path = FileDialog.getOpenFileName(self, file_dir=self._file_directory, ext_filter=self._ext) - file = file_path[0] or None - if file: + if file := file_path[0] or None: self.set_value(file) def _on_value_change(self, value=None): @@ -71,6 +70,5 @@ def _on_select_file(self): file_path = FileDialog.getSaveFileName(self, file_dir=self._file_directory, ext_filter=self._ext) - file = file_path[0] or None - if file: + if file := file_path[0] or None: self.set_value(file) diff --git a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_value_edit.py b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_value_edit.py index 157c55d7..66c5b413 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_value_edit.py +++ b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_value_edit.py @@ -15,8 +15,7 @@ def __init__(self, parent=None): self.last_action = None def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' # re-implemented. @@ -39,8 +38,7 @@ def mouseMoveEvent(self, event): """ self.mouseMove.emit(event) super(_NumberValueMenu, self).mouseMoveEvent(event) - action = self.actionAt(event.pos()) - if action: + if action := self.actionAt(event.pos()): if action is not self.last_action: self.stepChange.emit() self.last_action = action @@ -61,10 +59,7 @@ def set_steps(self, steps): def set_data_type(self, data_type): if data_type is int: - new_steps = [] - for step in self.steps: - if '.' not in str(step): - new_steps.append(step) + new_steps = [step for step in self.steps if '.' not in str(step)] self.set_steps(new_steps) elif data_type is float: self.set_steps(self.steps) @@ -97,8 +92,7 @@ def __init__(self, parent=None, data_type=float): self.set_data_type(data_type) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' # re-implemented @@ -170,7 +164,7 @@ def set_steps(self, steps=None): def get_value(self): if self.text().startswith('.'): - text = '0' + self.text() + text = f'0{self.text()}' self.setText(text) return self._convert_text(self.text()) diff --git a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_vectors.py b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_vectors.py index e29a6a5b..d448cf02 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/custom_widget_vectors.py +++ b/NodeGraphQt/custom_widgets/properties_bin/custom_widget_vectors.py @@ -42,8 +42,7 @@ def _on_value_change(self, value=None, index=None): def _update_items(self): if not isinstance(self._value, (list, tuple)): - raise TypeError('Value "{}" must be either list or tuple.' - .format(self._value)) + raise TypeError(f'Value "{self._value}" must be either list or tuple.') for index, value in enumerate(self._value): if (index + 1) > len(self._items): continue diff --git a/NodeGraphQt/custom_widgets/properties_bin/node_property_widgets.py b/NodeGraphQt/custom_widgets/properties_bin/node_property_widgets.py index 2923e26b..561c78b0 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/node_property_widgets.py +++ b/NodeGraphQt/custom_widgets/properties_bin/node_property_widgets.py @@ -88,9 +88,7 @@ def __init__(self, parent=None): layout.addLayout(self.__layout) def __repr__(self): - return '<{} object at {}>'.format( - self.__class__.__name__, hex(id(self)) - ) + return f'<{self.__class__.__name__} object at {hex(id(self))}>' def add_widget(self, name, widget, value, label=None): """ @@ -185,9 +183,7 @@ def __init__(self, parent=None, node=None): self._read_node(node) def __repr__(self): - return '<{} object at {}>'.format( - self.__class__.__name__, hex(id(self)) - ) + return f'<{self.__class__.__name__} object at {hex(id(self))}>' def _on_close(self): """ @@ -303,7 +299,7 @@ def add_tab(self, name): PropListWidget: tab child widget. """ if name in self.__tab_windows.keys(): - raise AssertionError('Tab name {} already taken!'.format(name)) + raise AssertionError(f'Tab name {name} already taken!') self.__tab_windows[name] = _PropertiesContainer(self) self.__tab.addTab(self.__tab_windows[name], name) return self.__tab_windows[name] @@ -321,8 +317,7 @@ def get_widget(self, name): if name == 'name': return self.name_wgt for tab_name, prop_win in self.__tab_windows.items(): - widget = prop_win.get_widget(name) - if widget: + if widget := prop_win.get_widget(name): return widget @@ -404,7 +399,7 @@ def __init__(self, parent=None, node_graph=None): node_graph.property_changed.connect(self.__on_graph_property_changed) def __repr__(self): - return '<{} object at {}>'.format(self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__} object at {hex(id(self))}>' def __on_prop_close(self, node_id): items = self._prop_list.findItems(node_id, QtCore.Qt.MatchExactly) @@ -488,8 +483,7 @@ def add_node(self, node): if rows >= self.limit(): self._prop_list.removeRow(rows - 1) - itm_find = self._prop_list.findItems(node.id, QtCore.Qt.MatchExactly) - if itm_find: + if itm_find := self._prop_list.findItems(node.id, QtCore.Qt.MatchExactly): self._prop_list.removeRow(itm_find[0].row()) self._prop_list.insertRow(0) @@ -539,8 +533,7 @@ def prop_widget(self, node): NodePropWidget: node property widget. """ node_id = node if isinstance(node, str) else node.id - itm_find = self._prop_list.findItems(node_id, QtCore.Qt.MatchExactly) - if itm_find: + if itm_find := self._prop_list.findItems(node_id, QtCore.Qt.MatchExactly): item = itm_find[0] return self._prop_list.cellWidget(item.row(), 0) diff --git a/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_abstract.py b/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_abstract.py index 86974647..3ba78740 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_abstract.py +++ b/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_abstract.py @@ -13,8 +13,7 @@ class BaseProperty(QtWidgets.QWidget): value_changed = QtCore.Signal(str, object) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def get_value(self): """ diff --git a/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_base.py b/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_base.py index 040458c5..b611157a 100644 --- a/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_base.py +++ b/NodeGraphQt/custom_widgets/properties_bin/prop_widgets_base.py @@ -10,8 +10,7 @@ class PropLabel(QtWidgets.QLabel): value_changed = QtCore.Signal(str, object) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def get_value(self): return self.text() @@ -35,8 +34,7 @@ def __init__(self, parent=None): self.editingFinished.connect(self._on_editing_finished) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def _on_editing_finished(self): self.value_changed.emit(self.toolTip(), self.text()) @@ -64,8 +62,7 @@ def __init__(self, parent=None): self._prev_text = '' def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def focusInEvent(self, event): super(PropTextEdit, self).focusInEvent(event) @@ -100,8 +97,7 @@ def __init__(self, parent=None): self.currentIndexChanged.connect(self._on_index_changed) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def _on_index_changed(self): self.value_changed.emit(self.toolTip(), self.get_value()) @@ -149,8 +145,7 @@ def __init__(self, parent=None): self.clicked.connect(self._on_clicked) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def _on_clicked(self): self.value_changed.emit(self.toolTip(), self.get_value()) @@ -178,8 +173,7 @@ def __init__(self, parent=None): self.valueChanged.connect(self._on_value_change) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def _on_value_change(self, value): self.value_changed.emit(self.toolTip(), value) @@ -206,8 +200,7 @@ def __init__(self, parent=None): self.valueChanged.connect(self._on_value_change) def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def _on_value_change(self, value): self.value_changed.emit(self.toolTip(), value) diff --git a/NodeGraphQt/nodes/backdrop_node.py b/NodeGraphQt/nodes/backdrop_node.py index 47e8c914..477de6e3 100644 --- a/NodeGraphQt/nodes/backdrop_node.py +++ b/NodeGraphQt/nodes/backdrop_node.py @@ -37,13 +37,13 @@ def on_backdrop_updated(self, update_prop, value=None): value (object): update value (optional) """ if update_prop == 'sizer_mouse_release': - self.graph.begin_undo('resized "{}"'.format(self.name())) + self.graph.begin_undo(f'resized "{self.name()}"') self.set_property('width', value['width']) self.set_property('height', value['height']) self.set_pos(*value['pos']) self.graph.end_undo() elif update_prop == 'sizer_double_clicked': - self.graph.begin_undo('"{}" auto resize'.format(self.name())) + self.graph.begin_undo(f'"{self.name()}" auto resize') self.set_property('width', value['width']) self.set_property('height', value['height']) self.set_pos(*value['pos']) @@ -53,7 +53,7 @@ def auto_size(self): """ Auto resize the backdrop node to fit around the intersecting nodes. """ - self.graph.begin_undo('"{}" auto resize'.format(self.name())) + self.graph.begin_undo(f'"{self.name()}" auto resize') size = self.view.calc_backdrop_size() self.set_property('width', size['width']) self.set_property('height', size['height']) @@ -69,7 +69,7 @@ def wrap_nodes(self, nodes): """ if not nodes: return - self.graph.begin_undo('"{}" wrap nodes'.format(self.name())) + self.graph.begin_undo(f'"{self.name()}" wrap nodes') size = self.view.calc_backdrop_size([n.view for n in nodes]) self.set_property('width', size['width']) self.set_property('height', size['height']) diff --git a/NodeGraphQt/nodes/base_node.py b/NodeGraphQt/nodes/base_node.py index d1595eb0..3b239218 100644 --- a/NodeGraphQt/nodes/base_node.py +++ b/NodeGraphQt/nodes/base_node.py @@ -307,8 +307,7 @@ def add_input(self, name='input', multi_input=False, display_name=True, NodeGraphQt.Port: the created port object. """ if name in self.inputs().keys(): - raise PortRegistrationError( - 'port name "{}" already registered.'.format(name)) + raise PortRegistrationError(f'port name "{name}" already registered.') port_args = [name, multi_input, display_name, locked] if painter_func and callable(painter_func): @@ -350,8 +349,7 @@ def add_output(self, name='output', multi_output=True, display_name=True, NodeGraphQt.Port: the created port object. """ if name in self.outputs().keys(): - raise PortRegistrationError( - 'port name "{}" already registered.'.format(name)) + raise PortRegistrationError(f'port name "{name}" already registered.') port_args = [name, multi_output, display_name, locked] if painter_func and callable(painter_func): @@ -423,8 +421,8 @@ def delete_input(self, port): return if not self.port_deletion_allowed(): raise PortError( - 'Port "{}" can\'t be deleted on this node because ' - '"ports_removable" is not enabled.'.format(port.name())) + f"""Port "{port.name()}" can\'t be deleted on this node because "ports_removable" is not enabled.""" + ) if port.locked(): raise PortError('Error: Can\'t delete a port that is locked!') self._inputs.remove(port) @@ -453,8 +451,8 @@ def delete_output(self, port): return if not self.port_deletion_allowed(): raise PortError( - 'Port "{}" can\'t be deleted on this node because ' - '"ports_removable" is not enabled.'.format(port.name())) + f"""Port "{port.name()}" can\'t be deleted on this node because "ports_removable" is not enabled.""" + ) if port.locked(): raise PortError('Error: Can\'t delete a port that is locked!') self._outputs.remove(port) @@ -684,7 +682,7 @@ def add_accept_port_type(self, port, port_type_data): """ node_ports = self._inputs + self._outputs if port not in node_ports: - raise PortError('Node does not contain port: "{}"'.format(port)) + raise PortError(f'Node does not contain port: "{port}"') self._model.add_port_accept_connection_type( port_name=port.name(), @@ -708,14 +706,11 @@ def accepted_port_types(self, port): """ ports = self._inputs + self._outputs if port not in ports: - raise PortError('Node does not contain port "{}"'.format(port)) + raise PortError(f'Node does not contain port "{port}"') - accepted_types = self.graph.model.port_accept_connection_types( - node_type=self.type_, - port_type=port.type_(), - port_name=port.name() + return self.graph.model.port_accept_connection_types( + node_type=self.type_, port_type=port.type_(), port_name=port.name() ) - return accepted_types def add_reject_port_type(self, port, port_type_data): """ @@ -744,7 +739,7 @@ def add_reject_port_type(self, port, port_type_data): """ node_ports = self._inputs + self._outputs if port not in node_ports: - raise PortError('Node does not contain port: "{}"'.format(port)) + raise PortError(f'Node does not contain port: "{port}"') self._model.add_port_reject_connection_type( port_name=port.name(), @@ -768,14 +763,11 @@ def rejected_port_types(self, port): """ ports = self._inputs + self._outputs if port not in ports: - raise PortError('Node does not contain port "{}"'.format(port)) + raise PortError(f'Node does not contain port "{port}"') - rejected_types = self.graph.model.port_reject_connection_types( - node_type=self.type_, - port_type=port.type_(), - port_name=port.name() + return self.graph.model.port_reject_connection_types( + node_type=self.type_, port_type=port.type_(), port_name=port.name() ) - return rejected_types def on_input_connected(self, in_port, out_port): """ diff --git a/NodeGraphQt/nodes/group_node.py b/NodeGraphQt/nodes/group_node.py index ecbc47ad..91d70e16 100644 --- a/NodeGraphQt/nodes/group_node.py +++ b/NodeGraphQt/nodes/group_node.py @@ -34,9 +34,7 @@ def is_expanded(self): Returns: bool: true if the node is expanded. """ - if not self.graph: - return False - return bool(self.id in self.graph.sub_graphs) + return False if not self.graph else self.id in self.graph.sub_graphs def get_sub_graph(self): """ @@ -78,8 +76,7 @@ def expand(self): Returns: SubGraph: node graph used to manage the nodes expaneded session. """ - sub_graph = self.graph.expand_group_node(self) - return sub_graph + return self.graph.expand_group_node(self) def collapse(self): """ @@ -93,9 +90,7 @@ def collapse(self): def set_name(self, name=''): super(GroupNode, self).set_name(name) - # update the tab bar and navigation labels. - sub_graph = self.get_sub_graph() - if sub_graph: + if sub_graph := self.get_sub_graph(): nav_widget = sub_graph.navigation_widget nav_widget.update_label_item(self.name(), self.id) @@ -155,8 +150,7 @@ def delete_input(self, port): if self.is_expanded: sub_graph = self.get_sub_graph() - port_node = sub_graph.get_node_by_port(port) - if port_node: + if port_node := sub_graph.get_node_by_port(port): sub_graph.remove_node(port_node, push_undo=False) super(GroupNode, self).delete_input(port) @@ -169,8 +163,7 @@ def delete_output(self, port): if self.is_expanded: sub_graph = self.get_sub_graph() - port_node = sub_graph.get_node_by_port(port) - if port_node: + if port_node := sub_graph.get_node_by_port(port): sub_graph.remove_node(port_node, push_undo=False) super(GroupNode, self).delete_output(port) diff --git a/NodeGraphQt/nodes/port_node.py b/NodeGraphQt/nodes/port_node.py index 7fc4e919..ff7109b5 100644 --- a/NodeGraphQt/nodes/port_node.py +++ b/NodeGraphQt/nodes/port_node.py @@ -43,8 +43,7 @@ def add_input(self, name='input', multi_input=False, display_name=True, This is not available for the ``PortInputNode`` class. """ raise PortRegistrationError( - '"{}.add_input()" is not available for {}.' - .format(self.__class__.__name__, self) + f'"{self.__class__.__name__}.add_input()" is not available for {self}.' ) def add_output(self, name='output', multi_output=True, display_name=True, @@ -56,8 +55,7 @@ def add_output(self, name='output', multi_output=True, display_name=True, """ if self._outputs: raise PortRegistrationError( - '"{}.add_output()" only ONE output is allowed for this node.' - .format(self.__class__.__name__, self) + f'"{self.__class__.__name__}.add_output()" only ONE output is allowed for this node.' ) super(PortInputNode, self).add_output( name=name, @@ -111,8 +109,7 @@ def add_input(self, name='input', multi_input=False, display_name=True, """ if self._inputs: raise PortRegistrationError( - '"{}.add_input()" only ONE input is allowed for this node.' - .format(self.__class__.__name__, self) + f'"{self.__class__.__name__}.add_input()" only ONE input is allowed for this node.' ) super(PortOutputNode, self).add_input( name=name, @@ -130,6 +127,5 @@ def add_output(self, name='output', multi_output=True, display_name=True, This is not available for the ``PortOutputNode`` class. """ raise PortRegistrationError( - '"{}.add_output()" is not available for {}.' - .format(self.__class__.__name__, self) + f'"{self.__class__.__name__}.add_output()" is not available for {self}.' ) diff --git a/NodeGraphQt/qgraphics/node_abstract.py b/NodeGraphQt/qgraphics/node_abstract.py index 29dfcf18..a064f91b 100644 --- a/NodeGraphQt/qgraphics/node_abstract.py +++ b/NodeGraphQt/qgraphics/node_abstract.py @@ -35,8 +35,7 @@ def __init__(self, name='node', parent=None): self._height = NodeEnum.HEIGHT.value def __repr__(self): - return '{}.{}(\'{}\')'.format( - self.__module__, self.__class__.__name__, self.name) + return f"{self.__module__}.{self.__class__.__name__}(\'{self.name}\')" def boundingRect(self): return QtCore.QRectF(0.0, 0.0, self._width, self._height) @@ -202,7 +201,7 @@ def name(self): @name.setter def name(self, name=''): self._properties['name'] = name - self.setToolTip('node: {}'.format(name)) + self.setToolTip(f'node: {name}') @property def properties(self): @@ -215,7 +214,7 @@ def properties(self): props = {'width': self.width, 'height': self.height, 'pos': self.xy_pos} - props.update(self._properties) + props |= self._properties return props def viewer(self): diff --git a/NodeGraphQt/qgraphics/node_backdrop.py b/NodeGraphQt/qgraphics/node_backdrop.py index 628d2186..10ee86db 100644 --- a/NodeGraphQt/qgraphics/node_backdrop.py +++ b/NodeGraphQt/qgraphics/node_backdrop.py @@ -41,8 +41,8 @@ def itemChange(self, change, value): if change == self.ItemPositionChange: item = self.parentItem() mx, my = item.minimum_size - x = mx if value.x() < mx else value.x() - y = my if value.y() < my else value.y() + x = max(value.x(), mx) + y = max(value.y(), my) value = QtCore.QPointF(x, y) item.on_sizer_pos_changed(value) return value @@ -127,8 +127,7 @@ def _combined_rect(self, nodes): return rect def mouseDoubleClickEvent(self, event): - viewer = self.viewer() - if viewer: + if viewer := self.viewer(): viewer.node_double_clicked.emit(self.id) super(BackdropNodeItem, self).mouseDoubleClickEvent(event) @@ -219,7 +218,7 @@ def paint(self, painter, option, widget): self.backdrop_text) if self.selected: - sel_color = [x for x in NodeEnum.SELECTED_COLOR.value] + sel_color = list(NodeEnum.SELECTED_COLOR.value) sel_color[-1] = 15 painter.setBrush(QtGui.QColor(*sel_color)) painter.setPen(QtCore.Qt.NoPen) @@ -250,15 +249,14 @@ def get_nodes(self, inc_intersects=False): rect = polygon.boundingRect() items = self.scene().items(rect, mode=mode[inc_intersects]) for item in items: - if item == self or item == self._sizer: + if item in [self, self._sizer]: continue if isinstance(item, AbstractNodeItem): nodes.append(item) return nodes def calc_backdrop_size(self, nodes=None): - nodes = nodes or self.get_nodes(True) - if nodes: + if nodes := nodes or self.get_nodes(True): nodes_rect = self._combined_rect(nodes) else: center = self.mapToScene(self.boundingRect().center()) diff --git a/NodeGraphQt/qgraphics/node_base.py b/NodeGraphQt/qgraphics/node_base.py index 15b91389..ad3157e9 100644 --- a/NodeGraphQt/qgraphics/node_base.py +++ b/NodeGraphQt/qgraphics/node_base.py @@ -245,8 +245,7 @@ def mouseDoubleClickEvent(self, event): event.ignore() return - viewer = self.viewer() - if viewer: + if viewer := self.viewer(): viewer.node_double_clicked.emit(self.id) super(NodeItem, self).mouseDoubleClickEvent(event) @@ -275,10 +274,10 @@ def _tooltip_disable(self, state): Args: state (bool): node disable state. """ - tooltip = '{}'.format(self.name) + tooltip = f'{self.name}' if state: tooltip += ' (DISABLED)' - tooltip += '
{}
'.format(self.type_) + tooltip += f'
{self.type_}
' self.setToolTip(tooltip) def _set_base_size(self, add_w=0.0, add_h=0.0): @@ -290,10 +289,8 @@ def _set_base_size(self, add_w=0.0, add_h=0.0): add_h (float): add additional height. """ self._width, self._height = self.calc_size(add_w, add_h) - if self._width < NodeEnum.WIDTH.value: - self._width = NodeEnum.WIDTH.value - if self._height < NodeEnum.HEIGHT.value: - self._height = NodeEnum.HEIGHT.value + self._width = max(self._width, NodeEnum.WIDTH.value) + self._height = max(self._height, NodeEnum.HEIGHT.value) def _set_text_color(self, color): """ @@ -561,9 +558,7 @@ def _align_ports_horizontal(self, v_offset): txt_offset = PortEnum.CLICK_FALLOFF.value - 2 spacing = 1 - # adjust input position - inputs = [p for p in self.inputs if p.isVisible()] - if inputs: + if inputs := [p for p in self.inputs if p.isVisible()]: port_width = inputs[0].boundingRect().width() port_height = inputs[0].boundingRect().height() port_x = (port_width / 2) * -1 @@ -577,9 +572,7 @@ def _align_ports_horizontal(self, v_offset): txt_x = port.boundingRect().width() / 2 - txt_offset text.setPos(txt_x, port.y() - 1.5) - # adjust output position - outputs = [p for p in self.outputs if p.isVisible()] - if outputs: + if outputs := [p for p in self.outputs if p.isVisible()]: port_width = outputs[0].boundingRect().width() port_height = outputs[0].boundingRect().height() port_x = width - (port_width / 2) @@ -595,9 +588,7 @@ def _align_ports_horizontal(self, v_offset): text.setPos(txt_x, port.y() - 1.5) def _align_ports_vertical(self, v_offset): - # adjust input position - inputs = [p for p in self.inputs if p.isVisible()] - if inputs: + if inputs := [p for p in self.inputs if p.isVisible()]: port_width = inputs[0].boundingRect().width() port_height = inputs[0].boundingRect().height() half_width = port_width / 2 @@ -608,9 +599,7 @@ def _align_ports_vertical(self, v_offset): port.setPos(port_x - half_width, port_y) port_x += delta - # adjust output position - outputs = [p for p in self.outputs if p.isVisible()] - if outputs: + if outputs := [p for p in self.outputs if p.isVisible()]: port_width = outputs[0].boundingRect().width() port_height = outputs[0].boundingRect().height() half_width = port_width / 2 @@ -810,14 +799,14 @@ def layout_direction(self, value=0): @AbstractNodeItem.width.setter def width(self, width=0.0): w, h = self.calc_size() - width = width if width > w else w + width = max(width, w) AbstractNodeItem.width.fset(self, width) @AbstractNodeItem.height.setter def height(self, height=0.0): w, h = self.calc_size() - h = 70 if h < 70 else h - height = height if height > h else h + h = max(h, 70) + height = max(height, h) AbstractNodeItem.height.fset(self, height) @AbstractNodeItem.disabled.setter @@ -922,10 +911,7 @@ def add_input(self, name='input', multi_port=False, display_name=True, Returns: PortItem: input port qgraphics item. """ - if painter_func: - port = CustomPortItem(self, painter_func) - else: - port = PortItem(self) + port = CustomPortItem(self, painter_func) if painter_func else PortItem(self) port.name = name port.port_type = PortTypeEnum.IN.value port.multi_connection = multi_port @@ -949,10 +935,7 @@ def add_output(self, name='output', multi_port=False, display_name=True, Returns: PortItem: output port qgraphics item. """ - if painter_func: - port = CustomPortItem(self, painter_func) - else: - port = PortItem(self) + port = CustomPortItem(self, painter_func) if painter_func else PortItem(self) port.name = name port.port_type = PortTypeEnum.OUT.value port.multi_connection = multi_port @@ -1021,10 +1004,9 @@ def add_widget(self, widget): self._widgets[widget.get_name()] = widget def get_widget(self, name): - widget = self._widgets.get(name) - if widget: + if widget := self._widgets.get(name): return widget - raise NodeWidgetError('node has no widget "{}"'.format(name)) + raise NodeWidgetError(f'node has no widget "{name}"') def has_widget(self, name): return name in self._widgets.keys() diff --git a/NodeGraphQt/qgraphics/node_circle.py b/NodeGraphQt/qgraphics/node_circle.py index 07bb0c7e..0ea8e4a7 100644 --- a/NodeGraphQt/qgraphics/node_circle.py +++ b/NodeGraphQt/qgraphics/node_circle.py @@ -25,20 +25,18 @@ def _align_ports_horizontal(self, v_offset): node_center_y = self.boundingRect().center().y() node_center_y += v_offset - # adjust input position - inputs = [p for p in self.inputs if p.isVisible()] - if inputs: + if inputs := [p for p in self.inputs if p.isVisible()]: port_width = inputs[0].boundingRect().width() port_height = inputs[0].boundingRect().height() count = len(inputs) + # top half + port_x = (port_width / 2) * -1 + port_y = node_center_y - (port_height / 2) if count > 2: is_odd = bool(count % 2) - middle_idx = int(count / 2) + middle_idx = count // 2 - # top half - port_x = (port_width / 2) * -1 - port_y = node_center_y - (port_height / 2) for idx, port in enumerate(reversed(inputs[:middle_idx])): if idx == 0: if is_odd: @@ -62,8 +60,6 @@ def _align_ports_horizontal(self, v_offset): port_y += port_height + spacing else: - port_x = (port_width / 2) * -1 - port_y = node_center_y - (port_height / 2) inputs[0].setPos(port_x, port_y - (port_height / 2) + spacing) inputs[1].setPos(port_x, port_y + (port_height / 2) + spacing) @@ -74,20 +70,18 @@ def _align_ports_horizontal(self, v_offset): txt_x = port.pos().x() + port_width - txt_offset text.setPos(txt_x, port.y() - 1.5) - # adjust output position - outputs = [p for p in self.outputs if p.isVisible()] - if outputs: + if outputs := [p for p in self.outputs if p.isVisible()]: port_width = outputs[0].boundingRect().width() port_height = outputs[0].boundingRect().height() count = len(outputs) + # top half + port_x = width - (port_width / 2) + port_y = node_center_y - (port_height / 2) if count > 2: is_odd = bool(count % 2) - middle_idx = int(count / 2) + middle_idx = count // 2 - # top half - port_x = width - (port_width / 2) - port_y = node_center_y - (port_height / 2) for idx, port in enumerate(reversed(outputs[:middle_idx])): if idx == 0: if is_odd: @@ -110,8 +104,6 @@ def _align_ports_horizontal(self, v_offset): port_x -= (port_width / 2) - (txt_offset / 2) port_y += port_height + spacing else: - port_x = width - (port_width / 2) - port_y = node_center_y - (port_height / 2) outputs[0].setPos(port_x, port_y - (port_height / 2) + spacing) outputs[1].setPos(port_x, port_y + (port_height / 2) + spacing) diff --git a/NodeGraphQt/qgraphics/node_group.py b/NodeGraphQt/qgraphics/node_group.py index 5b6a69e0..bdab459c 100644 --- a/NodeGraphQt/qgraphics/node_group.py +++ b/NodeGraphQt/qgraphics/node_group.py @@ -193,9 +193,7 @@ def _align_ports_horizontal(self, v_offset): txt_offset = PortEnum.CLICK_FALLOFF.value - 2 spacing = 1 - # adjust input position - inputs = [p for p in self.inputs if p.isVisible()] - if inputs: + if inputs := [p for p in self.inputs if p.isVisible()]: port_width = inputs[0].boundingRect().width() port_height = inputs[0].boundingRect().height() port_x = port_width / 2 * -1 @@ -211,9 +209,7 @@ def _align_ports_horizontal(self, v_offset): txt_x += 3.0 text.setPos(txt_x, port.y() - 1.5) - # adjust output position - outputs = [p for p in self.outputs if p.isVisible()] - if outputs: + if outputs := [p for p in self.outputs if p.isVisible()]: port_width = outputs[0].boundingRect().width() port_height = outputs[0].boundingRect().height() port_x = width - (port_width / 2) @@ -230,9 +226,7 @@ def _align_ports_horizontal(self, v_offset): text.setPos(txt_x, port.y() - 1.5) def _align_ports_vertical(self, v_offset): - # adjust input position - inputs = [p for p in self.inputs if p.isVisible()] - if inputs: + if inputs := [p for p in self.inputs if p.isVisible()]: port_width = inputs[0].boundingRect().width() port_height = inputs[0].boundingRect().height() half_width = port_width / 2 @@ -243,9 +237,7 @@ def _align_ports_vertical(self, v_offset): port.setPos(port_x - half_width, port_y) port_x += delta - # adjust output position - outputs = [p for p in self.outputs if p.isVisible()] - if outputs: + if outputs := [p for p in self.outputs if p.isVisible()]: port_width = outputs[0].boundingRect().width() port_height = outputs[0].boundingRect().height() half_width = port_width / 2 diff --git a/NodeGraphQt/qgraphics/node_port_in.py b/NodeGraphQt/qgraphics/node_port_in.py index b5c23618..a7315060 100644 --- a/NodeGraphQt/qgraphics/node_port_in.py +++ b/NodeGraphQt/qgraphics/node_port_in.py @@ -23,7 +23,7 @@ def __init__(self, name='group port', parent=None): def _set_base_size(self, add_w=0.0, add_h=0.0): width, height = self.calc_size(add_w, add_h) self._width = width + 60 - self._height = height if height >= 60 else 60 + self._height = max(height, 60) def _paint_horizontal(self, painter, option, widget): self.auto_switch_mode() diff --git a/NodeGraphQt/qgraphics/node_port_out.py b/NodeGraphQt/qgraphics/node_port_out.py index 733b0043..16278931 100644 --- a/NodeGraphQt/qgraphics/node_port_out.py +++ b/NodeGraphQt/qgraphics/node_port_out.py @@ -23,7 +23,7 @@ def __init__(self, name='group port', parent=None): def _set_base_size(self, add_w=0.0, add_h=0.0): width, height = self.calc_size(add_w, add_h) self._width = width + 60 - self._height = height if height >= 60 else 60 + self._height = max(height, 60) def _paint_horizontal(self, painter, option, widget): self.auto_switch_mode() diff --git a/NodeGraphQt/qgraphics/pipe.py b/NodeGraphQt/qgraphics/pipe.py index fde52d95..ff257726 100644 --- a/NodeGraphQt/qgraphics/pipe.py +++ b/NodeGraphQt/qgraphics/pipe.py @@ -55,8 +55,7 @@ def __init__(self, input_port=None, output_port=None): def __repr__(self): in_name = self._input_port.name if self._input_port else '' out_name = self._output_port.name if self._output_port else '' - return '{}.Pipe(\'{}\', \'{}\')'.format( - self.__module__, in_name, out_name) + return f"{self.__module__}.Pipe(\'{in_name}\', \'{out_name}\')" def hoverEnterEvent(self, event): self.activate() @@ -64,9 +63,7 @@ def hoverEnterEvent(self, event): def hoverLeaveEvent(self, event): self.reset() if self.input_port and self.output_port: - if self.input_port.node.selected: - self.highlight() - elif self.output_port.node.selected: + if self.input_port.node.selected or self.output_port.node.selected: self.highlight() if self.isSelected(): self.highlight() @@ -385,10 +382,9 @@ def port_from_pos(self, pos, reverse=False): input_dist = self._calc_distance(inport_pos, pos) output_dist = self._calc_distance(outport_pos, pos) if input_dist < output_dist: - port = self.output_port if reverse else self.input_port + return self.output_port if reverse else self.input_port else: - port = self.input_port if reverse else self.output_port - return port + return self.input_port if reverse else self.output_port def viewer(self): """ @@ -403,8 +399,7 @@ def viewer_pipe_layout(self): Returns: int: pipe layout mode. """ - viewer = self.viewer() - if viewer: + if viewer := self.viewer(): return viewer.get_pipe_layout() def viewer_layout_direction(self): @@ -412,8 +407,7 @@ def viewer_layout_direction(self): Returns: int: graph layout mode. """ - viewer = self.viewer() - if viewer: + if viewer := self.viewer(): return viewer.get_layout_direction() def set_pipe_styling(self, color, width=0.5, style=0): @@ -493,9 +487,7 @@ def disabled(self): """ if self.input_port and self.input_port.node.disabled: return True - if self.output_port and self.output_port.node.disabled: - return True - return False + return bool(self.output_port and self.output_port.node.disabled) @property def input_port(self): @@ -503,10 +495,7 @@ def input_port(self): @input_port.setter def input_port(self, port): - if isinstance(port, PortItem) or not port: - self._input_port = port - else: - self._input_port = None + self._input_port = port if isinstance(port, PortItem) or not port else None @property def output_port(self): @@ -514,10 +503,7 @@ def output_port(self): @output_port.setter def output_port(self, port): - if isinstance(port, PortItem) or not port: - self._output_port = port - else: - self._output_port = None + self._output_port = port if isinstance(port, PortItem) or not port else None @property def color(self): @@ -628,7 +614,7 @@ def draw_index_pointer(self, start_port, cursor_pos, color=None): else: transform.rotate(90) self._idx_text.setPos(*text_pos) - self._idx_text.setPlainText('{}'.format(start_port.name)) + self._idx_text.setPlainText(f'{start_port.name}') self._idx_pointer.setPolygon(transform.map(self._poly)) diff --git a/NodeGraphQt/qgraphics/port.py b/NodeGraphQt/qgraphics/port.py index 78c8a0ad..c8e1f22f 100644 --- a/NodeGraphQt/qgraphics/port.py +++ b/NodeGraphQt/qgraphics/port.py @@ -33,10 +33,10 @@ def __init__(self, parent=None): self._locked = False def __str__(self): - return '{}.PortItem("{}")'.format(self.__module__, self.name) + return f'{self.__module__}.PortItem("{self.name}")' def __repr__(self): - return '{}.PortItem("{}")'.format(self.__module__, self.name) + return f'{self.__module__}.PortItem("{self.name}")' def boundingRect(self): return QtCore.QRectF(0.0, 0.0, @@ -157,14 +157,14 @@ def connected_pipes(self): @property def connected_ports(self): - ports = [] port_types = { PortTypeEnum.IN.value: 'output_port', PortTypeEnum.OUT.value: 'input_port' } - for pipe in self.connected_pipes: - ports.append(getattr(pipe, port_types[self.port_type])) - return ports + return [ + getattr(pipe, port_types[self.port_type]) + for pipe in self.connected_pipes + ] @property def hovered(self): @@ -227,7 +227,7 @@ def locked(self): def locked(self, value=False): self._locked = value conn_type = 'multi' if self.multi_connection else 'single' - tooltip = '{}: ({})'.format(self.name, conn_type) + tooltip = f'{self.name}: ({conn_type})' if value: tooltip += ' (L)' self.setToolTip(tooltip) @@ -239,7 +239,7 @@ def multi_connection(self): @multi_connection.setter def multi_connection(self, mode=False): conn_type = 'multi' if mode else 'single' - self.setToolTip('{}: ({})'.format(self.name, conn_type)) + self.setToolTip(f'{self.name}: ({conn_type})') self._multi_connection = mode @property diff --git a/NodeGraphQt/widgets/actions.py b/NodeGraphQt/widgets/actions.py index 4af371eb..5f02fb45 100644 --- a/NodeGraphQt/widgets/actions.py +++ b/NodeGraphQt/widgets/actions.py @@ -38,9 +38,9 @@ def __init__(self, *args, **kwargs): } stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' stylesheet += style self.setStyleSheet(stylesheet) diff --git a/NodeGraphQt/widgets/dialogs.py b/NodeGraphQt/widgets/dialogs.py index fd88d95a..eaa41f64 100644 --- a/NodeGraphQt/widgets/dialogs.py +++ b/NodeGraphQt/widgets/dialogs.py @@ -22,8 +22,7 @@ def getSaveFileName(parent=None, title='Save File', file_dir=None, file_dir = _current_user_directory file_dlg = QtWidgets.QFileDialog.getSaveFileName( parent, title, file_dir, ext_filter) - file = file_dlg[0] or None - if file: + if file := file_dlg[0] or None: set_dir(file) return file_dlg @@ -34,8 +33,7 @@ def getOpenFileName(parent=None, title='Open File', file_dir=None, file_dir = _current_user_directory file_dlg = QtWidgets.QFileDialog.getOpenFileName( parent, title, file_dir, ext_filter) - file = file_dlg[0] or None - if file: + if file := file_dlg[0] or None: set_dir(file) return file_dlg @@ -59,4 +57,4 @@ def question_dialog(text='', title='Are you sure?'): QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No ) result = dlg.exec_() - return bool(result == QtWidgets.QMessageBox.Yes) + return result == QtWidgets.QMessageBox.Yes diff --git a/NodeGraphQt/widgets/node_graph.py b/NodeGraphQt/widgets/node_graph.py index b50117b2..2644ee2d 100644 --- a/NodeGraphQt/widgets/node_graph.py +++ b/NodeGraphQt/widgets/node_graph.py @@ -52,9 +52,9 @@ def __init__(self, parent=None): } stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' stylesheet += style self.setStyleSheet(stylesheet) diff --git a/NodeGraphQt/widgets/node_widgets.py b/NodeGraphQt/widgets/node_widgets.py index a494bfaa..4a02f040 100644 --- a/NodeGraphQt/widgets/node_widgets.py +++ b/NodeGraphQt/widgets/node_widgets.py @@ -38,11 +38,7 @@ def setTitleAlign(self, align='center'): 'padding': '0px', } } - if self.title(): - style_dict['QGroupBox']['padding-top'] = '14px' - else: - style_dict['QGroupBox']['padding-top'] = '2px' - + style_dict['QGroupBox']['padding-top'] = '14px' if self.title() else '2px' if align == 'center': style_dict['QGroupBox::title']['subcontrol-position'] = 'top center' elif align == 'left': @@ -53,9 +49,9 @@ def setTitleAlign(self, align='center'): style_dict['QGroupBox::title']['margin-right'] = '4px' stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' stylesheet += style self.setStyleSheet(stylesheet) @@ -101,7 +97,7 @@ def __init__(self, parent=None, name=None, label=''): def setToolTip(self, tooltip): tooltip = tooltip.replace('\n', '
') - tooltip = '{}
{}'.format(self.name, tooltip) + tooltip = f'{self.name}
{tooltip}' super(NodeBaseWidget, self).setToolTip(tooltip) def on_value_changed(self, *args, **kwargs): @@ -345,9 +341,9 @@ def __init__(self, parent=None, name='', label='', text=''): } stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' stylesheet += style ledit = QtWidgets.QLineEdit() @@ -408,9 +404,9 @@ def __init__(self, parent=None, name='', label='', text='', state=False): } stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' stylesheet += style _cbox.setStyleSheet(stylesheet) diff --git a/NodeGraphQt/widgets/scene.py b/NodeGraphQt/widgets/scene.py index 91e7ccfa..9f65a758 100644 --- a/NodeGraphQt/widgets/scene.py +++ b/NodeGraphQt/widgets/scene.py @@ -15,8 +15,7 @@ def __init__(self, parent=None): def __repr__(self): cls_name = str(self.__class__.__name__) - return '<{}("{}") object at {}>'.format( - cls_name, self.viewer(), hex(id(self))) + return f'<{cls_name}("{self.viewer()}") object at {hex(id(self))}>' # def _draw_text(self, painter, pen): # font = QtGui.QFont() @@ -45,11 +44,10 @@ def _draw_grid(self, painter, rect, pen, grid_size): first_left = left - (left % grid_size) first_top = top - (top % grid_size) - lines = [] - lines.extend([ + lines = [ QtCore.QLineF(x, top, x, bottom) for x in range(first_left, right, grid_size) - ]) + ] lines.extend([ QtCore.QLineF(left, y, right, y) for y in range(first_top, bottom, grid_size)] diff --git a/NodeGraphQt/widgets/tab_search.py b/NodeGraphQt/widgets/tab_search.py index 477342f8..20f9c7e6 100644 --- a/NodeGraphQt/widgets/tab_search.py +++ b/NodeGraphQt/widgets/tab_search.py @@ -79,9 +79,9 @@ def __init__(self, parent=None): } stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' stylesheet += style self.setStyleSheet(stylesheet) @@ -140,9 +140,9 @@ def __init__(self, node_dict=None): } self._menu_stylesheet = '' for css_class, css in style_dict.items(): - style = '{} {{\n'.format(css_class) + style = f'{css_class} {{\n' for elm_name, elm_val in css.items(): - style += ' {}:{};\n'.format(elm_name, elm_val) + style += f' {elm_name}:{elm_val};\n' style += '}\n' self._menu_stylesheet += style self.setStyleSheet(self._menu_stylesheet) @@ -158,7 +158,7 @@ def __init__(self, node_dict=None): self._wire_signals() def __repr__(self): - return '<{} at {}>'.format(self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__} at {hex(id(self))}>' def keyPressEvent(self, event): super(TabSearchMenuWidget, self).keyPressEvent(event) @@ -170,8 +170,7 @@ def _fuzzy_finder(key, collection): pattern = '.*?'.join(key.lower()) regex = re.compile(pattern) for item in collection: - match = regex.search(item.lower()) - if match: + if match := regex.search(item.lower()): suggestions.append((len(match.group()), match.start(), item)) return [x for _, _, x in sorted(suggestions)] @@ -231,8 +230,7 @@ def _on_search_submitted(self): return text = action.text() - node_type = self._node_dict.get(text) - if node_type: + if node_type := self._node_dict.get(text): self.search_submitted.emit(node_type) self._close() @@ -301,7 +299,7 @@ def set_nodes(self, node_dict=None): self._node_dict[name] = node_types[0] continue for node_id in node_types: - self._node_dict['{} ({})'.format(name, node_id)] = node_id + self._node_dict[f'{name} ({node_id})'] = node_id self.build_menu_tree() self.rebuild = False diff --git a/NodeGraphQt/widgets/viewer.py b/NodeGraphQt/widgets/viewer.py index 70ee0109..2651310f 100644 --- a/NodeGraphQt/widgets/viewer.py +++ b/NodeGraphQt/widgets/viewer.py @@ -158,8 +158,7 @@ def __init__(self, parent=None, undo_stack=None): self.reject_connection_types = None def __repr__(self): - return '<{}() object at {}>'.format( - self.__class__.__name__, hex(id(self))) + return f'<{self.__class__.__name__}() object at {hex(id(self))}>' def focusInEvent(self, event): """ @@ -357,8 +356,7 @@ def contextMenuEvent(self, event): if ctx_menus['nodes'].isEnabled(): pos = self.mapToScene(self._previous_pos) items = self._items_near(pos) - nodes = [i for i in items if isinstance(i, AbstractNodeItem)] - if nodes: + if nodes := [i for i in items if isinstance(i, AbstractNodeItem)]: node = nodes[0] ctx_menu = ctx_menus['nodes'].get_menu(node.type_, node.id) if ctx_menu: @@ -526,11 +524,11 @@ def mouseReleaseEvent(self, event): rect_items = self.scene().items( self.mapToScene(rect).boundingRect() ) - node_ids = [] - for item in rect_items: - if isinstance(item, AbstractNodeItem): - node_ids.append(item.id) - + node_ids = [ + item.id + for item in rect_items + if isinstance(item, AbstractNodeItem) + ] # emit the node selection signals. if node_ids: prev_ids = [ diff --git a/NodeGraphQt/widgets/viewer_nav.py b/NodeGraphQt/widgets/viewer_nav.py index ef809e71..ea4c1a16 100644 --- a/NodeGraphQt/widgets/viewer_nav.py +++ b/NodeGraphQt/widgets/viewer_nav.py @@ -49,7 +49,7 @@ def paint(self, painter, option, index): y = rect.top() + m + 2 h = rect.height() - (m * 2) - 2 painter.setBrush(itm_color) - for i in range(4): + for _ in range(4): itm_rect = QtCore.QRectF(x, y, 1.3, h) painter.drawRoundedRect(itm_rect, 1.0, 1.0) x += 2.0 diff --git a/docs/_themes/sphinx_rtd_theme/__init__.py b/docs/_themes/sphinx_rtd_theme/__init__.py index 75e6e751..137a7395 100644 --- a/docs/_themes/sphinx_rtd_theme/__init__.py +++ b/docs/_themes/sphinx_rtd_theme/__init__.py @@ -24,8 +24,7 @@ def get_html_theme_path(): """Return list of HTML theme paths.""" - cur_dir = path.abspath(path.dirname(path.dirname(__file__))) - return cur_dir + return path.abspath(path.dirname(path.dirname(__file__))) def config_initiated(app, config): diff --git a/docs/conf.py b/docs/conf.py index 23199416..fb335f5f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -26,10 +26,10 @@ project = 'NodeGraphQt' author = NodeGraphQt.pkg_info.__author__ -copyright = '{}, {}'.format(datetime.now().year, author) +copyright = f'{datetime.now().year}, {author}' # The full version, including alpha/beta/rc tags -release = '{}'.format(NodeGraphQt.VERSION) +release = f'{NodeGraphQt.VERSION}' # The short X.Y version version = '{0}.{1}'.format(*NodeGraphQt.VERSION.split('.')) diff --git a/examples/hotkeys/hotkey_functions.py b/examples/hotkeys/hotkey_functions.py index ab1b5233..c4ed1ba4 100644 --- a/examples/hotkeys/hotkey_functions.py +++ b/examples/hotkeys/hotkey_functions.py @@ -47,8 +47,7 @@ def open_session(graph): Prompts a file open dialog to load a session. """ current = graph.current_session() - file_path = graph.load_dialog(current) - if file_path: + if file_path := graph.load_dialog(current): graph.load_session(file_path) @@ -57,8 +56,7 @@ def import_session(graph): Prompts a file open dialog to load a session. """ current = graph.current_session() - file_path = graph.load_dialog(current) - if file_path: + if file_path := graph.load_dialog(current): graph.import_session(file_path) @@ -66,10 +64,9 @@ def save_session(graph): """ Prompts a file save dialog to serialize a session if required. """ - current = graph.current_session() - if current: + if current := graph.current_session(): graph.save_session(current) - msg = 'Session layout saved:\n{}'.format(current) + msg = f'Session layout saved:\n{current}' viewer = graph.viewer() viewer.message_dialog(msg, title='Session Saved') else: @@ -81,8 +78,7 @@ def save_session_as(graph): Prompts a file save dialog to serialize a session. """ current = graph.current_session() - file_path = graph.save_dialog(current) - if file_path: + if file_path := graph.save_dialog(current): graph.save_session(file_path)