PyObjC Framework: libdispatch
Wrappers for libdispatch on macOS, a low-level C API for concurrent code execution. PyObjC acts as a bridge between Python and Objective-C, enabling Python scripts to seamlessly utilize and extend Objective-C class libraries, including Apple's high-level system APIs. It allows for the development of full-featured Cocoa applications entirely in Python. The current version is 12.1 and follows the PyObjC release cadence.
Warnings
- breaking PyObjC 12.x (and thus `pyobjc-framework-libdispatch` 12.x) dropped support for Python 3.9. Similarly, PyObjC 11.x dropped support for Python 3.8. The current version of PyObjC and its framework wrappers require Python 3.10 or later.
- breaking PyObjC 10.3 introduced a change that broke `__init__` methods in Python subclasses of Objective-C classes if they implicitly relied on PyObjC's default `__new__` behavior without defining their own `__new__`. While partially reverted in 10.3.1, classes that implement `__init__` but not `__new__` and rely on PyObjC's `__new__` might still exhibit issues.
- gotcha `libdispatch` exposes a low-level C API. Incorrect usage of its functions and types through PyObjC can bypass Python's usual error handling, leading to hard crashes or undefined behavior in your application rather than graceful Python exceptions.
- deprecated The primary import for this framework is `import dispatch`. While `import libdispatch` currently functions for backward compatibility, it is considered the older name for the package. Future PyObjC versions may remove support for the `libdispatch` import name.
- gotcha Several `libdispatch` functions, such as `dispatch_retain`, `dispatch_release`, `dispatch_wait`, `dispatch_notify`, `dispatch_cancel`, and `dispatch_testcancel`, are either unavailable or require specific usage patterns (e.g., using object-specific variants). Additionally, the workgroup APIs introduced in macOS 11 are not supported.
Install
-
pip install pyobjc-framework-libdispatch
Imports
- dispatch
import dispatch
Quickstart
import array
from dispatch import dispatch_once
# dispatch_once ensures a block of code is executed only once,
# even if called multiple times from different threads.
# It requires an array.array instance as its first argument
# to track whether the block has been run.
predicate = array.array('l', [0]) # Must be a mutable array of long (C 'long')
def my_initialization_function():
print("Performing one-time initialization...")
# Simulate some work
import time
time.sleep(0.1)
print("Initialization complete.")
print("Attempting to call dispatch_once for the first time...")
dispatch_once(predicate, my_initialization_function)
print("Attempting to call dispatch_once for the second time...")
dispatch_once(predicate, my_initialization_function)
print("Program finished.")