PyObjC Core

12.1 · active · verified Thu Apr 09

PyObjC Core is the essential bridge between Python and Objective-C, enabling Python applications to interact with macOS Cocoa frameworks. Version 12.1 is current, and releases typically align with new macOS SDKs and Python versions, with major versions appearing roughly annually and patches more frequently.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates fundamental PyObjC interoperability, including converting Python types to Objective-C types, interacting with core Cocoa framework classes (like NSString and NSDate from Foundation), and defining Objective-C classes in Python. For this example to run, `pip install pyobjc` (which includes `pyobjc-core` and common frameworks like Foundation) is recommended.

import objc
from Foundation import NSString, NSDate, NSObject

# 1. Basic interoperability: Python string to Objective-C NSString
python_string = "Hello from PyObjC!"
objc_string = NSString.stringWithString_(python_string)
print(f"Python string: '{python_string}' (Type: {type(python_string)})\n")
print(f"Objective-C NSString: '{objc_string}' (Type: {type(objc_string)})\n")

# 2. Get current date as NSDate
current_nsdate = NSDate.date()
print(f"Current NSDate: {current_nsdate} (Type: {type(current_nsdate)})\n")

# 3. Define a Python class that inherits from an Objective-C class
@objc.python_class
class MyPythonObject(NSObject):
    def init(self):
        self = objc.super(MyPythonObject, self).init()
        if self is None: return None
        self.message = "I am a Python-backed Objective-C object!"
        return self

    # Expose a method callable from Objective-C (and Python)
    @objc.selector('myCustomMethod')
    def myCustomMethod(self):
        return self.message

# Create an instance and call the method
# Note: alloc().init() is the standard Objective-C way to create objects.
python_objc_instance = MyPythonObject.alloc().init()
print(f"Message from Python-backed ObjC instance: {python_objc_instance.myCustomMethod()}\n")

view raw JSON →