PyObjC GameplayKit
PyObjC-framework-gameplaykit provides Python bindings for Apple's GameplayKit framework on macOS. It enables Python applications to leverage game development utilities, including random number generation, pathfinding, AI behaviors, and more, directly from Python. The current version is 12.1, with releases generally aligning with macOS SDK updates.
Warnings
- breaking PyObjC 12.0 dropped support for Python 3.9, and PyObjC 11.0 dropped support for Python 3.8. Users upgrading should ensure their Python environment meets the new minimum requirement (currently Python 3.10+).
- gotcha PyObjC 11.1 changed how initializer methods (like `init`) handle reference counting, aligning with `clang`'s ARC documentation. Methods in the 'init' family now correctly steal a reference to `self` and return a new one. This could subtly affect memory management or object lifecycle in applications directly interacting with low-level Objective-C object creation.
- gotcha Experimental free-threading support (PEP 703) in Python 3.13 is *not fully stable or supported* in PyObjC 11. While changes were made to enable it, relying on it for production or performance-critical applications is not recommended.
- gotcha In PyObjC 10.3, direct calls to `__init__` were restricted when a class used PyObjC's `__new__` implementation. Version 10.3.1 reintroduced the ability to use `__init__` if the user provided their own `__new__` or a superclass did. Code relying on PyObjC's default `__new__` still cannot use `__init__`.
- gotcha The `os.fspath()` function in Python will raise a `TypeError` when used with Cocoa URLs (`NSURL`, `CFURLRef`) that do not refer to local filesystem paths (e.g., web URLs). This change in behavior ensures `os.fspath()` correctly reflects only local filesystem paths.
Install
-
pip install pyobjc-framework-gameplaykit
Imports
- GameplayKit
import GameplayKit
- GKRandomSource
from GameplayKit import GKRandomSource
Quickstart
import GameplayKit
import objc # For general PyObjC operations, though not explicitly used here beyond object instantiation
# Initialize a basic random number generator from GameplayKit
# The alloc().init() pattern is common for Objective-C object creation
random_source = GameplayKit.GKARC4RandomSource.alloc().init()
# Generate a random integer within a bound (0 to 99)
random_int = random_source.nextIntWithUpperBound_(100)
print(f"Generated random number (0-99): {random_int}")
# Example using a different random distribution
shuffled_array = random_source.arrayByShufflingObjectsInArray_(["apple", "banana", "cherry", "date"])
print(f"Shuffled array: {shuffled_array}")