Utilities API

This is the utilities API reference. Here you will details about different Hyprpy utility classes.

Signals

A basic implementation of the observer pattern for emitting signals and connecting listeners to them, similar to the Django signals framework.

This module allows objects to declare signals that other parts of the application can connect callbacks to. When the signal is emitted, all connected callbacks are executed.

Example:

from hyprpy.utils.signals import Signal

class MyClass:
    def __init__(self):
        self.my_signal = Signal(sender=self)

    def perform_action(self):
        self.my_signal.emit(info="Action performed!")

def my_callback(sender, **kwargs):
    print(f"{sender} says: {kwargs['info']}")

obj = MyClass()
obj.my_signal.connect(my_callback)
obj.perform_action()
# Output: <MyClass object at 0x...> says: Action performed!
seealso:

Components: Reacting to events

class Signal(sender: object)

Bases: object

A signal that can have multiple observers (callbacks) connected to it.

Each time the signal is emitted, all connected callbacks are executed. When instantiating a signal, the sending object (sender) must be passed to the signal’s constructor.

Parameters:

sender – The source object sending the signal.

Example:

class MyClass:
    def __init__(self):
        self.my_signal = Signal(sender=self)

    def do_something(self):
        self.my_signal.emit(action="something_done")

obj = MyClass()
connect(callback: Callable) None

Connects the specified callback to this Signal.

The callback signature must contain sender as the positional argument, followed by **kwargs.

Parameters:

callback – The callback function to be connected to this signal.

Raises:

TypeError if callback is not callable.

Raises:

ValueError if the first positional argument of callback is not sender.

Raises:

ValueError if callback does not accept keyword arguments.

Example:

def my_callback(sender, **kwargs):
    print(sender, kwargs)

obj.signal.connect(my_callback)
disconnect(callback: Callable) None

Disconnects the specified callback from this Signal.

This is useful if you want to limit how often a callback should be executed.

Parameters:

callback – The callback function to be disconnected.

Raises:

ValueError if the specified callback is not in the list of observers.

Example:

def my_callback(sender, **kwargs):
    print(sender, kwargs)

obj.signal.connect(my_callback)
...
# some time later
...
signal.disconnect(my_callback)
emit(**kwargs) None

Emits the signal, notifying all observers by calling their callback functions.

Any information to be sent to the observers should be provided as keyword arguments to this method.

Parameters:

**kwargs – Keyword arguments that will be passed to each callback.

Example:

def my_callback(sender, **kwargs):
    print(kwargs['message'])

obj.signal.connect(my_callback)
...
obj.signal.emit(message="Hello from sender!")

Sockets

Interfaces for UNIX socket operations with Hyprland’s event and command sockets.

Hyprland offers two UNIX sockets:

  1. EventSocket: This socket broadcasts various events occurring in the Hyprland session, e.g., windows or workspaces getting created or destroyed.

  2. CommandSocket: This socket can be written to in order to influence Hyprland’s behavior or send queries about the current state.

Hyprpy uses standard library sockets for socket operations.

Examples:

from hyprpy import Hyprland

instance = Hyprland()

# Connect the socket, wait for an event to occur, print the event data and close the socket.
instance.event_socket.connect()
instance.event_socket.wait()
data = instance.even_socket.read()
print(data)
instance.event_socket.close()

# Send a command
instance.command_socket.send_command("dispatch", flags=["--single-instance"], args=["exec", "kitty"])
exception SocketError

Bases: Exception

Raised when a socket operation fails.

class AbstractSocket(signature: str)

Bases: ABC

Base class for concrete socket classes.

Provides attributes and methods common between EventSocket and CommandSocket.

Upon initialization, the underlying socket object is not created. Users must explicitly call connect() prior to using the socket, and should call close() afterwards.

connect(timeout: int | float | None = 1) None

Creates and connects the socket.

If a timeout is set, its value specifies the number of seconds to wait until the connection is established. If the connection cannot be established within the specified timeout period, a SocketError is raised. The default timeout is 1 second.

Once created, the socket is put into non-blocking mode (regardless of the specified timeout).

Parameters:

timeout – Maximum number of seconds to wait for a connection to be established until a SocketError is raised. If timeout is None, the call blocks indefinitely until a connection is established.

Raises:

SocketError if the socket has already been connected, or if the connection attempt takes longer than timeout seconds.

close() None

Disconnects and closes the socket.

Raises:

SocketError if the socket has already been disconnected.

send(data: str) None

Sends data into the socket.

Raises:

SocketError if the socket is not connected.

wait(timeout: int | float | None = None) None

Waits a maximum of timeout seconds until data has arrived at the socket.

Calling this method avoids using active waiting to wait for socket data.

Parameters:

timeout – The maximum number of seconds to wait for data until a SocketError is raised. If timeout is None, wait indefinitely until data is ready to be retrieved.

Raises:

SocketError if the socket is not connected, or if the specified timeout was reached..

read() str

Immediately retrieves all data from the socket and returns it.

Returns:

The data received from the socket as a string. If the socket does not contain any data, returns an empty string.

Raises:

SocketError if the socket is not connected.

class EventSocket(signature: str)

Bases: AbstractSocket

Interface to Hyprland’s event socket.

This socket broadcasts events about the ongoing Hyprland session, such as windows or workspaces being created or destroyed.

class CommandSocket(signature: str)

Bases: AbstractSocket

Interface to Hyprland’s command socket.

Provides the CommandSocket.send_command() method, which can be used to send a wide range of commands, as explained in the Hyprland wiki.

send_command(command: str, flags: List[str] = [], args: List[str] = []) str

Sends a command through the socket and returns the received response.

Contrary to the methods inherited from AbstractSocket, this method implicitly connects the socket prior to sending the command, and disconnects it afterwards.

The command syntax and options are the same as when using hyprctl, but the hyprctl part can be omitted. Read the wiki entry for more information.

Parameters:
  • command – The command string.

  • flags – Any flags to accompany the command.

  • args – Arguments for the command.

Returns:

Response from the socket.

Raises:

SocketError if the socket is already connected.

Raises:

TypeError if command or any items in flags and args are not strings.

Raises:

ValueError if command or any items in flags and args are empty strings.

Example:

response = command_socket.send_command("clients", flags=["-j"])
# response contains JSON listing all Hyprland clients

Shell

Utilities for shell-related operations.

exception NonZeroStatusException

Bases: Exception

Raised when a shell invocation returns a non-zero exit status.

exception EnvironmentException

Bases: Exception

Raised when an expected environment variable could not be found.

run_or_fail(command: list[str]) Tuple[str, str]

Runs the specified command successfully and returns its output, or raises an exception.

Each command token must be an item in the command list. Each token is treated as a contiguous string by the shell (even if it contains whitespace).

Example:

from hyprpy.utils.shell import run_or_fail

cmd = ['echo', 'Hello world!']
response = run_or_fail(cmd)
print(response)[0]
# Output: 'Hello world!\n'
print(response)[1]
# Output: ''
Parameters:

command – The command to run, as a list of string tokens.

Returns:

A tuple containing the command’s output on stdout and stderr respectively.

Raises:

NonZeroStatusException if the invoked command returned a non-zero exit status.

Raises:

TypeError if command is not a list of strings.

Raises:

ValueError if command is an empty list.

get_env_var_or_fail(name: str) str

Retrieves the value of the environment variable name or raises an exception if it is undefined.

Parameters:

name – Name of the environment variable to retrieve.

Returns:

The current value of the environment variable.

Raises:

EnvironmentException if the specified environment variable is undefined.

Raises:

TypeError if name is not a string.

Raises:

ValueError if name is an empty string.

Assertions

Utility functions for type- and sanity checking.

assert_is_bool(value: Any) None

Raises an exception if value is not a boolean.

Parameters:

value – The input to check.

Raises:

TypeError if value is not a boolean.

assert_is_int(value: Any) None

Raises an exception if value is not an integer.

Parameters:

value – The input to check.

Raises:

TypeError if value is not a integer.

assert_is_float_or_int(value: Any) None

Raises an exception if value is not a floating point number or an integer.

Parameters:

value – The input to check.

Raises:

TypeError if value is not a floating point number or an integer.

assert_is_string(value: Any) None

Raises an exception if value is not a string.

Parameters:

value – The input to check.

Raises:

TypeError if value is not a string.

assert_is_nonempty_string(value: Any) None

Raises an exception if value is not a string of length >= 1.

Parameters:

value – The input to check.

Raises:

TypeError if value is not a string.

Raises:

ValueError if value is an empty string.

assert_is_hexadecimal_string(value: Any) None

Raises an exception if value is not a valid string representation of a hexadecimal number.

Parameters:

value – The input to check.

Raises:

TypeError if value is not a string.

Raises:

ValueError if value is empty, or not a valid hexadecimal string.

assert_is_callable(value: Any) None

Raises an exception if value is not callable.

Parameters:

value – The input to check.

Raises:

TypeError if value is not callable.

assert_is_callable_and_has_first_param_sender(value: Any) None

Raises an exception if value` is not a callable which has ``sender as its first positional argument.

Parameters:

value – The input to check.

Raises:

TypeError if value is not callable.

Raises:

ValueError if value` does not accept ``sender as its first positional argument.

assert_is_callable_and_accepts_kwargs(value: Any) None

Raises an exception if value is not a callable which accepts keyword arguments.

Parameters:

value – The input to check.

Raises:

TypeError if value is not callable.

Raises:

ValueError if value does not accept keyword arguments.