PyObjC Framework: libdispatch

12.1 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates the use of `dispatch_once` from the `libdispatch` bindings to ensure a function runs only a single time across application execution. Note the requirement for an `array.array('l', [0])` as the predicate argument for `dispatch_once`.

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.")

view raw JSON →