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:
- 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 thisSignal
.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
ifcallback
is not callable.- Raises:
ValueError
if the first positional argument ofcallback
is notsender
.- Raises:
ValueError
ifcallback
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 thisSignal
.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:
EventSocket: This socket broadcasts various events occurring in the Hyprland session, e.g., windows or workspaces getting created or destroyed.
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
andCommandSocket
.Upon initialization, the underlying
socket
object is not created. Users must explicitly callconnect()
prior to using thesocket
, and should callclose()
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 specifiedtimeout
period, aSocketError
is raised. The defaulttimeout
is 1 second.Once created, the
socket
is put into non-blocking mode (regardless of the specifiedtimeout
).- Parameters:
timeout – Maximum number of seconds to wait for a connection to be established until a
SocketError
is raised. Iftimeout
isNone
, the call blocks indefinitely until a connection is established.- Raises:
SocketError
if thesocket
has already been connected, or if the connection attempt takes longer thantimeout
seconds.
- close() None ¶
Disconnects and closes the
socket
.- Raises:
SocketError
if thesocket
has already been disconnected.
- send(data: str) None ¶
Sends
data
into thesocket
.- Raises:
SocketError
if thesocket
is not connected.
- wait(timeout: int | float | None = None) None ¶
Waits a maximum of
timeout
seconds until data has arrived at thesocket
.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. Iftimeout
isNone
, wait indefinitely until data is ready to be retrieved.- Raises:
SocketError
if thesocket
is not connected, or if the specifiedtimeout
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 thesocket
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 thehyprctl
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 thesocket
is already connected.- Raises:
TypeError
ifcommand
or any items inflags
andargs
are not strings.- Raises:
ValueError
ifcommand
or any items inflags
andargs
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
ifcommand
is not a list of strings.- Raises:
ValueError
ifcommand
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
ifname
is not a string.- Raises:
ValueError
ifname
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
is not a string.- Raises:
ValueError
ifvalue
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
ifvalue
is not a string.- Raises:
ValueError
ifvalue
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
ifvalue
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
ifvalue
is not callable.- Raises:
ValueError
ifvalue` 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
ifvalue
is not callable.- Raises:
ValueError
ifvalue
does not accept keyword arguments.