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:
objectA 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 (
object) – 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
callbackto thisSignal.The callback signature must contain
senderas the positional argument, followed by**kwargs.- Parameters:
callback (
Callable) – The callback function to be connected to this signal.- Raises:
TypeErrorifcallbackis not callable.- Raises:
ValueErrorif the first positional argument ofcallbackis notsender.- Raises:
ValueErrorifcallbackdoes 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
callbackfrom thisSignal.This is useful if you want to limit how often a callback should be executed.
- Parameters:
callback (
Callable) – The callback function to be disconnected.- Raises:
ValueErrorif 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 (
dict[str, any]) – 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!")
- class DeprecatedSignal(sender: object, deprecated_signal_name: str, replacement_signal_name: str | None)¶
Bases:
SignalBehaves just like a normal
Signal, but logs a deprecation warning to the console.A warning message is printed to the log when this Signal is connected to a callback.
- Parameters:
sender (
object) – The source object sending the signal.deprecated_signal_name (
str) – The name of the deprecated signal.replacement_signal_name (
str, optional) – The name of the new signal, if applicable, to use in favour of the deprecated one.
Example:
signal = DeprecatedSignal("Instance.signal_workspace_created", "Instance.signals.workspace")
- connect(callback: Callable) None¶
Connects the specified
callbackto thisSignal.The callback signature must contain
senderas the positional argument, followed by**kwargs.- Parameters:
callback (
Callable) – The callback function to be connected to this signal.- Raises:
TypeErrorifcallbackis not callable.- Raises:
ValueErrorif the first positional argument ofcallbackis notsender.- Raises:
ValueErrorifcallbackdoes 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
callbackfrom thisSignal.This is useful if you want to limit how often a callback should be executed.
- Parameters:
callback (
Callable) – The callback function to be disconnected.- Raises:
ValueErrorif 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 (
dict[str, any]) – 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:
ExceptionRaised when a socket operation fails.
- class AbstractSocket(signature: str)¶
Bases:
ABCBase class for concrete socket classes.
Provides attributes and methods common between
EventSocketandCommandSocket.Upon initialization, the underlying
socketobject 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
timeoutis set, its value specifies the number of seconds to wait until the connection is established. If the connection cannot be established within the specifiedtimeoutperiod, aSocketErroris raised. The defaulttimeoutis 1 second.Once created, the
socketis 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
SocketErroris raised. IftimeoutisNone, the call blocks indefinitely until a connection is established.- Raises:
SocketErrorif thesockethas already been connected, or if the connection attempt takes longer thantimeoutseconds.
- close() None¶
Disconnects and closes the
socket.- Raises:
SocketErrorif thesockethas already been disconnected.
- send(data: str) None¶
Sends
datainto thesocket.- Raises:
SocketErrorif thesocketis not connected.
- wait(timeout: int | float | None = None) None¶
Waits a maximum of
timeoutseconds 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
SocketErroris raised. IftimeoutisNone, wait indefinitely until data is ready to be retrieved.- Raises:
SocketErrorif thesocketis not connected, or if the specifiedtimeoutwas reached..
- read() str¶
Immediately retrieves all data from the
socketand returns it.- Returns:
The data received from the
socketas a string. If the socket does not contain any data, returns an empty string.- Raises:
SocketErrorif thesocketis not connected.
- class EventSocket(signature: str)¶
Bases:
AbstractSocketInterface 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:
AbstractSocketInterface 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 thehyprctlpart 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:
SocketErrorif thesocketis already connected.- Raises:
TypeErrorifcommandor any items inflagsandargsare not strings.- Raises:
ValueErrorifcommandor any items inflagsandargsare 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:
ExceptionRaised when a shell invocation returns a non-zero exit status.
- exception EnvironmentException¶
Bases:
ExceptionRaised when an expected environment variable could not be found.
- run_or_fail(command: list[str]) Tuple[str, str]¶
Runs the specified
commandsuccessfully and returns its output, or raises an exception.Each command token must be an item in the
commandlist. 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:
NonZeroStatusExceptionif the invoked command returned a non-zero exit status.- Raises:
TypeErrorifcommandis not a list of strings.- Raises:
ValueErrorifcommandis an empty list.
- get_env_var_or_fail(name: str) str¶
Retrieves the value of the environment variable
nameor 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:
EnvironmentExceptionif the specified environment variable is undefined.- Raises:
TypeErrorifnameis not a string.- Raises:
ValueErrorifnameis an empty string.
Assertions¶
Utility functions for type- and sanity checking.
- assert_is_bool(value: Any) None¶
Raises an exception if
valueis not a boolean.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not a boolean.
- assert_is_int(value: Any) None¶
Raises an exception if
valueis not an integer.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not a integer.
- assert_is_float_or_int(value: Any) None¶
Raises an exception if
valueis not a floating point number or an integer.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not a floating point number or an integer.
- assert_is_string(value: Any) None¶
Raises an exception if
valueis not a string.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not a string.
- assert_is_nonempty_string(value: Any) None¶
Raises an exception if
valueis not a string of length >= 1.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not a string.- Raises:
ValueErrorifvalueis an empty string.
- assert_is_hexadecimal_string(value: Any) None¶
Raises an exception if
valueis not a valid string representation of a hexadecimal number.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not a string.- Raises:
ValueErrorifvalueis empty, or not a valid hexadecimal string.
- assert_is_callable(value: Any) None¶
Raises an exception if
valueis not callable.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not callable.
- assert_is_callable_and_has_first_param_sender(value: Any) None¶
Raises an exception if
value` is not a callable which has ``senderas its first positional argument.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not callable.- Raises:
ValueErrorifvalue` does not accept ``senderas its first positional argument.
- assert_is_callable_and_accepts_kwargs(value: Any) None¶
Raises an exception if
valueis not a callable which accepts keyword arguments.- Parameters:
value – The input to check.
- Raises:
TypeErrorifvalueis not callable.- Raises:
ValueErrorifvaluedoes not accept keyword arguments.