Skip to content

general

Mihaly Konda edited this page Nov 12, 2025 · 5 revisions

general

Version: v1.1.3

A module for general utilities for the package.

class BijectiveDict [src]

A custom dictionary providing bijective mapping between a main type and a hashable secondary type. It works like a two-way dictionary as in each key-value pair is a value-key pair as well. The keys() method returns all keys, or optionally just the primary ones, while the values() method returns all values or optionally just the secondary ones (classic keys and values).

[src]

def __init__(self, primary_type: type) -> None

Initializer for the class.

Parameters:

  • primary_type: The type of the main keys for keys() and values().

[src]

def __getitem__(self, item: Any) -> Any

Returns a value from the internal dictionary accessed with '[]' (either of the main or the secondary type).

Parameters:

  • item: The key whose associated value is to be returned.

Returns: The (primary/secondary type) value associated with the key.


[src]

def __setitem__(self, key: Any, value: Any) -> None

Sets/updates a key-value pair in a bijective way.

Parameters:

  • key: Usually the object of primary type.
  • value: Usually the object of secondary type.

[src]

def __delitem__(self, item: Any) -> None

Deletes a key-value pair in a bijective way.

Parameters:

  • item: Usually the object of primary type.

[src]

def __len__(self) -> int

Returns the adjusted size of the internal dictionary.


[src]

def __repr__(self) -> str

Returns the repr of the internal dictionary.


[src]

def keys(self, primary_only: bool = True) -> list | tuple[list, list]

Returns the keys of the internal dictionary.

Parameters:

  • primary_only: A flag to only return the keys of the primary type (default behaviour).

Returns: Either a list of keys of the primary type or additionally a list of keys of the secondary type.


[src]

def values(self, secondary_only: bool = True) -> list | tuple[list, list]

Returns the values of the internal dictionary.

Parameters:

  • secondary_only: A flag to only return the keys of the secondary type (default behaviour).

Returns: Either a list of values of the secondary type or additionally (as the first item of the return tuple) a list of values of the primary type.


Example usage (from the colours module):

class _Colours(metaclass=Singleton):
    """ A src of colours of the standard R colour palette. """

    def __init__(self) -> None:
        """ Initializer for the class. """

        with open(os.path.join(_PACKAGE_DIR, 'colour_list.json'), 'r') as f:
            colours = json.load(f)

            self._colours_int = BijectiveDict(int)
            self._colours_str = BijectiveDict(str)
            for idx, colour_data in enumerate(colours):
                colour = Colour(colour_data['name'], *colour_data['rgb'])
                self._colours_int[idx] = colour
                self._colours_str[colour.name] = colour

    # === Code cut for demonstrational purposes ===

    def __getitem__(self, index: int | Colour | str) \
            -> int | Colour | tuple[Colour, int]:
        """
        Returns a value from one of the internal dictionaries accessed with '[]'
        (either of the main or the secondary type).

        :param index: The key whose associated value is to be returned.

        :returns: A Colour object, its index or a tuple of these, based on
            the type of the `index`.
        """

        if isinstance(index, int | Colour):
            return self._colours_int[index]
        else:  # str
            colour = self._colours_str[index]  # Might need to be moved to a f()
            return colour, self._colours_int[colour]  # (Colour, int)

The _Colours class provides multiple ways to access the stored colours: self._colours_int provides index-based, self._colours_str provides name-based access to colours. As shown in __getitem__(), when accessing either by an integer index or a colour object it returns the other, while when accessing by its name it returns a tuple of the colour object and the corresponding integer index.


class ReadOnlyDescriptor [src]

Read-only descriptor for use with protected storage attributes.

[src]

def __set_name__(self, owner: type, name: str) -> None

Sets the name of the storage attribute.

Parameters:

  • owner: The managed class.
  • name: The managed attribute's name.

[src]

def __get__(self, instance: Any, instance_type: type = None) -> Any

Returns the value of the protected storage attribute.

Parameters:

  • instance: An instance of the managed class (managed instance).
  • instance_type: Reference to the managed class, unused here.

Returns: Either the descriptor object itself or the value in the storage attribute.


[src]

def __set__(self, instance: Any, value: Any) -> Never

Sets the value of the protected storage attribute (would, but read-only).

Parameters:

  • instance: An instance of the managed class (managed instance).
  • value: The value to set for the storage attribute.

Raises: AttributeError: Notifies the user about the attribute being read-only.


class SignalBlocker(Generic[_T]) [src]

Temporarily blocks the signals of the handled QObject.

[src]

def __init__(self, obj: _T) -> None

Initializer for the class.

Parameters:

  • obj: An object whose signals should be blocked temporarily.

[src]

def __enter__(self) -> _T

Blocks the signals of the handled QObject.

Returns: The handled object.


[src]

def __exit__(self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> None

Unblocks the signals of the handled QObject.


Example usage:

with SignalBlocker(self._cmbTestCombobox) as obj:
    obj.setCurrentIndex(3)  # The `currentIndexChanged` signal is not emitted

Note that since it uses a generic type, type checkers will see the actual type of the blocked object (obj).


class Singleton(type) [src]

A metaclass making instance classes singletons.

[src]

def __call__(cls, *args, **kwargs) -> Any

Returns the existing instance or creates a new one.


function qt_connect() [src]

def qt_connect(signal: Callable, slot: Callable, unique: bool = False) -> None

Connects a Qt signal to a slot method. It uses the new-style connection creation, while having a simple signature and removing the need to sprinkle 'type: ignore' around connections.

Parameters:

  • signal: The signal of a Qt-object.
  • slot: A method of a class serving as a slot for the signal.
  • unique: Whether the connection should be set to unique. The default is False.

function resource_path() [src]

def resource_path(relative_path: str) -> str

Get absolute path to resource (for apps built with PyInstaller).

Parameters:

  • relative_path: A string representing a relative path to the requested resource.

Returns: The absolute path to the requested resource (as a simple string).


function parse_script() [src]

def parse_script(filename: str) -> ast.Module

Parses a source code file and returns its AST.

Parameters:

  • filename: The name of the file to parse.

Returns: The abstract syntax tree (AST) representation of the script passed to the function by its name, used for further processing in stub file generation.


function get_imports() [src]

def get_imports(filename: str) -> str

Returns a formatted string containing imports of the given file.

Parameters:

  • filename: The name of the script acquired by __file__.

Returns: A copy of the import list from the top of the file with 2 extra trailing carriage returns.


function get_functions() [src]

def get_functions(filename: str, ignores: None | list[str] = None) -> list[str]

Returns a list of the names of functions defined in the file, excluding those in ignores.

Parameters:

  • filename: The name of the script acquired by __file__.
  • ignores: A list of function names to ignore. The default is None.

Returns: A list of function names by which the function objects themselves can be retrieved using the globals() of the caller script.


Example use:

functions = [globals().get(func_name) for func_name
             in get_functions(__file__, ignores=['_init_module'])]

function get_classes() [src]

def get_classes(filename: str, ignores: None | list[str] = None) -> dict[str, None | list[str]]

Returns a list of the names of classes defined in the file, excluding those in ignores.

Parameters:

  • filename: The name of the script acquired by __file__.
  • ignores: A list of class names to ignore. The default is None.

Returns: A list of class names by which the class types themselves can be retrieved using the globals() of the caller script.


Example use:

classes = {globals().get(cls_name): signals
           for cls_name, signals in get_classes(__file__).items()}

function _stub_repr_function_like() [src]

def _stub_repr_function_like(f: cached_property | FunctionType | MethodType, class_bound: bool) -> str

Creates a stub representation for a function-like object.

Parameters:

  • f: The function-like object whose stub representation is to be made.
  • class_bound: A flag to add 'self' to the representation.

Returns: The stub representation of the input function-like object.


function stub_repr() [src]

def stub_repr(obj: object, signals: list[str] | None = None, extra_cvs: str | None = None, add_getattr: bool = False) -> str

Creates a specifically formatted stub representation of an object. Static methods must be changed to class methods for them to be compatible with the function (which cannot yet handle static methods). Dunder methods are usually not included (apart from __init__ or when requested a special __getattr__.)

Parameters:

  • obj: The object whose stub representation is to be made.
  • signals: A list of strings representing the (Qt) signals of the object, as [sigName(carriedType1, ...)]. The default is None.
  • extra_cvs: A string of extra class variables that are not defined as CVs in the source code. The default is None.
  • add_getattr: A flag for adding a special __getattr__ method to the repr. For public Qt-based classes, it needs so that the static type checker does not warn about variables declared outside __init__. The default is False.

These stub creator functions are for internal use mainly but you can see examples for their usage at the bottom of modules in the write_stub() functions.

API reference

Base/technical modules:

Other modules

Clone this wiki locally