PyObjC

12.1 · active · verified Mon Apr 13

PyObjC is a bridge between Python and Objective-C, allowing Python scripts to use and extend existing Objective-C class libraries, most importantly Apple's Cocoa. It enables the development of full-featured macOS applications in pure Python and seamless integration with Objective-C, C, and C++ code. PyObjC (version 12.1) is actively maintained and typically releases new versions aligning with macOS SDK updates and Python version support.

Warnings

Install

Imports

Quickstart

This example demonstrates fundamental PyObjC interactions: creating Objective-C `NSString` and `NSArray` objects, calling their methods, accessing PyObjC's `objc.YES`/`NO`/`nil` constants, and using `objc.autorelease_pool` for memory management.

import objc
from Foundation import NSString, NSArray

# Working with Objective-C classes
hello = NSString.stringWithString_("Hello, World!")
print(f"Hello string length: {hello.length()}") # Expected: 13

# Creating and using Objective-C objects
# Note the 'None' to signify the end of the variadic arguments for arrayWithObjects_
my_array = NSArray.arrayWithObjects_("foo", "bar", "baz", None)
print(f"Array count: {my_array.count()}") # Expected: 3
print(f"Object at index 1: {my_array.objectAtIndex_(1)}") # Expected: bar

# Using the bridge constants
print(f"objc.YES: {objc.YES}") # Expected: True
print(f"objc.NO: {objc.NO}")  # Expected: False
print(f"objc.nil: {objc.nil}") # Expected: None

# Proper memory management with autorelease pools (good practice for intensive ops)
with objc.autorelease_pool():
    temp_strings = []
    for i in range(5):
        temp_string = NSString.stringWithFormat_("Item %d", i)
        temp_strings.append(temp_string)
    print(f"Temporary strings created: {len(temp_strings)}")
    # Objects are automatically released when the pool exits

view raw JSON →