Bridge and SDK Search
Cocoa that reads like Swift: properties, kwarg selectors, and value bridging on top of pyobjc.
pyobjc has twenty years of irreplaceable metadata (C function signatures, (value, error) out-param tupling, block signatures), but Cocoa code written with it reads as ceremony: f.setDateFormat_('yyyy'), str(e.title()), saveEvent_span_error_. Swift's niceness over the same APIs is a finite list of mechanical transforms, and fastcocoa applies them to pyobjc classes in place:
from fastcocoa.eventkit import EKEvent, EKEventStore
s = EKEventStore()
ev = EKEvent(eventStore=s, title=title, startDate=start)
s.save(ev, span='thisEvent')
Everything is real pyobjc underneath: the same objects, delegates, and framework coverage.
Setup: import through the stubs
Importing a class through a framework stub pythonifies it, and no other setup exists. Stubs exist for foundation, appkit, eventkit, contacts, photos, avfoundation, and speech; for anything else, pythonify(cls, mod=Framework) is the primitive they wrap. Named imports only: import * from a stub sweeps nothing.
The bridge
- Declared properties are real Python descriptors, generated from the ObjC runtime's own metadata.
ev.title = twrites, and reads convert:NSStringtostr,NSDatetodatetime,NSDatatobytes,NSNumbertobool/int/float, containers recursively, lists tofastcore'sL. - Keyword arguments are assembled into selectors:
o.saveEvent(ev, span=x)callssaveEvent:span:error:, and a trailingerror:out-param raises instead of returning (chkdoes the same for raw calls). A string passed where an integer enum belongs resolves by unique constant suffix, sospan='thisEvent'findsEKSpanThisEvent. - Constructor kwargs reach class factories,
initWith...initializers, and settable properties in one call:EKEvent(eventStore=s, title=t, startDate=d). - Indexed collections (
count/objectAtIndex:) getlen, indexing, lazy iteration, and anL-stylemap, sofirst(PHAsset.fetchAssets(options=o))and.map(f)both work. - Every object returned through the bridge is swept (pythonified) on the way out, so private cluster subclasses and KVO-swizzled instances behave like their public ancestors.
Swift names
Beyond the runtime's own metadata, fastcocoa reads Apple's Swift symbol graphs, so methods also answer to their curated Swift names, with the argument labels every Swift tutorial shows:
s.save(ev, span='thisEvent', commit=True) # saveEvent:span:commit:error:
f.string(from_=d) # stringFromDate: (a keyword label takes a trailing underscore)
await store.requestFullAccessToEvents() # the importer's async variant, as an awaitable
EKSpan.thisEvent # enum cases as namespaces, importable from the stubs
Where Swift knows a parameter's class, an omitted one is built from leftover kwargs: session.dataTask(URL=u) constructs the NSURLRequest for dataTask(with:). The ObjC spellings keep working, and remain the only spelling for selectors outside the public SDK surface. Extraction runs once per SDK version and needs the Xcode Command Line Tools; without a toolchain, fastcocoa warns once and the ObjC spellings still work.
Browse and search the SDK
The same tables carry Apple's header docs, so the surface is discoverable without leaving Python:
- A pending call documents itself:
doc(s.save),s.save?, andinspect.signatureshow the real labels, parameter classes, per-parameter docs, and a developer.apple.com link, with overloads stacked in the docstring.dir(o)includes the Swift heads. sdkclass('EKEventStore')is one class as a markdown reference: methods and inits with signatures and abstracts, plus declared properties.sdkgroups('EventKit')is a whole framework as an attribute-chained tree, andfull_docs(sdkgroups('EventKit'))renders it as one markdown document, sized for LLM context.sdksearch(pattern, frameworks=None, kind=None)searches methods, inits, enums, and properties across extracted frameworks, matching names, labels, param and property types, and doc text, so "which methods take aPHFetchOptions" issdksearch('PHFetchOptions')and "delete a reminder" issdksearch('remove.*reminder').kind=filters'im'/'cm'/'init'/'protocol'/'enum'/'property'. Search never extracts a table silently; passframeworks=to opt in.
The search flow, end to end:
hits = sdksearch('capture.*screen|screen.*captur')
hits # numbered previews: 1 AVCaptureScreenInput.init(displayID): *Creates an ...*
hits[1] # that hit in full: line, docs URL, typed params
c = hits[1].caller(AVCaptureScreenInput) # the hit's call bound to a receiver: for an init hit the class itself, else a caller documented as that exact overload
c(displayID=CGMainDisplayID()) # construct it
Helpers
sortd('-creationDate,title') builds NSSortDescriptor lists. nsurl/nsdate/pydate/topy convert values by hand where needed. Sig awaits a Cocoa callback from the event loop; wait_cb is its blocking twin for worker threads, with a ... argument marking where the callback goes. camera is a running capture session as a context manager. fastcocoa.swifttool holds the symbol-graph extractor plus Swift build/sign/bundle helpers for making small signed apps. The escape hatch from all conversion is pyobjc's own: o.pyobjc_instanceMethods.title() bypasses every descriptor.
Framework stubs and pythonify
pythonify
def pythonify(
*classes, # Objective-C classes to patch in place
mod=None, # Framework module (e.g. `EventKit`), for resolving string enum names in calls
):
Give Cocoa classes Swift-grade Python ergonomics, in place.
Declared properties become converted Python descriptors, keyword calls like o.saveEvent(ev, span=x) assemble saveEvent:span:error: (raising on trailing error out-params), and EKEvent(eventStore=s) reaches class factories and settable properties. Ancestry properties are attached directly on each leaf class so they win pyobjc's selector cache, and classes reached through object properties are swept too. Idempotent; untouched pyobjc classes are unaffected.
modattr
def modattr(
mod, n:str
):
Framework stub __getattr__: classes arrive pythonified, and Objective-C enum type names arrive as case namespaces.
Value conversion and errors
Swept properties and method return values convert Cocoa primitives (NSString, NSDate, NSData, NSNumber, containers) to Python equivalents automatically and raise on trailing error: out-parameters. Call these functions when converting values explicitly or unpacking raw pyobjc results.
chk
def chk(
res:tuple
):
Unpack a Cocoa (value, error) or (ok, error) out-param pair, raising RuntimeError on failure.
topy
def topy(
o
):
Convert a Cocoa value to its Python equivalent recursively (str, datetime, bytes, bool/int/float, dict, L); other Cocoa objects pass through with their live class swept.
sortd
def sortd(
spec:str, # Comma-separated keys, each optionally prefixed `-` for descending, e.g. `'-creationDate'`
)->list: # List of `NSSortDescriptor` objects
An NSSortDescriptor list from a compact spec, for the many Cocoa APIs that take one
nsurl
def nsurl(
path:str | pathlib._local.Path
):
Convert a filesystem path (expanding ~) to a file NSURL.
nsdate
def nsdate(
dt:datetime.datetime
):
Convert a Python datetime to an NSDate.
pydate
def pydate(
d
)->datetime.datetime | None:
Convert an NSDate (or None) to a local Python datetime.
from datetime import datetime
dt = datetime(2025, 1, 2, 3, 4, 5)
assert pydate(nsdate(dt)) == dt
assert len(sortd('-creationDate,title')) == 2
Callbacks and camera capture
Use Sig to bridge a Cocoa completion block into asyncio, wait_cb() for the blocking equivalent on a worker thread, and camera() for a running capture session on the default camera.
Sig
def Sig():
Await a Cocoa callback from the loop: pass sig.set (any thread or queue) and await sig.wait(secs)
Sig.set
def set():
Signal waiting coroutines from any thread or dispatch queue.
Sig.wait
async def wait(
secs:float, # Seconds before TimeoutError
):
wait_cb
def wait_cb(
f, # Called as `f(*args, **kwargs)` with each `...` replaced by the completion callback
*args, # Positional args for `f`; `...` marks the callback slot
secs:float=10, # Seconds before TimeoutError
**kwargs
)->list: # Callback arguments converted through `topy`
Blocking twin of Sig for worker-thread bodies: call f, return the callback's args as Python values
camera
def camera():
A running capture session on the default camera, yielding its photo output
Browsing and searching the SDK
fastcocoa distills Apple's Swift symbol graphs and header comments into searchable Python tables. Search never triggers extraction silently; pass frameworks= to opt in.
sdkops
def sdkops(
framework:str, # Apple framework name
head:str, # Swift method or init head name
entries:list[dict], # Distilled table entries for `head`
)->list[fastcocoa.surface.SdkOp]: # Documented `SdkOp` records with overload variants stacked in each docstring
Build SdkOp records for head's distilled table entries.
sdkclass
def sdkclass(
c, # Class object, instance, or Objective-C class name string
framework:str=None, # Framework name, needed only when `c` is a string not in any loaded table
)->fastcocoa.surface.SdkGroup: # Browsable class reference with methods, inits, and declared properties
Return one class as a browsable Markdown reference with signatures, abstracts, and declared properties.
sdkgroups
def sdkgroups(
framework:str
)->dict[str, fastcocoa.surface.SdkGroup]:
Return a whole framework as {framework: root_group} of attribute-chained SdkGroup objects; pass to full_docs for one Markdown reference.
sdksearch
def sdksearch(
pattern:str, # Regular expression (smart-case, like `rg`) matched against names, labels, parameter types, and doc text
frameworks=None, # Framework name(s) to search, extracting tables if needed; default searches every already-extracted framework
kind:str=None, # Filter: `'im'`, `'cm'`, `'init'`, `'protocol'`, `'enum'`, or `'property'`
)->fastcocoa.surface.SdkHits: # Matching `SdkHit` records as numbered previews
Search extracted SDK tables across methods, inits, protocols, enums, and properties.
full_docs
def full_docs(
groups
):
Markdown overview of every group and operation in a mk_groups tree.