---
title: Bridge and SDK Search
description: 'Cocoa that reads like Swift: properties, kwarg selectors, and value
  bridging on top of pyobjc.'
order: 1
---
`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`](fastcocoa.md) applies them to `pyobjc` classes in place:

```python
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 = t` writes, and reads convert: `NSString` to `str`, `NSDate` to `datetime`, `NSData` to `bytes`, `NSNumber` to `bool`/`int`/`float`, containers recursively, lists to `fastcore`'s `L`.
- Keyword arguments are assembled into selectors: `o.saveEvent(ev, span=x)` calls `saveEvent:span:error:`, and a trailing `error:` out-param raises instead of returning ([`chk`](fastcocoa.md#chk) does the same for raw calls). A string passed where an integer enum belongs resolves by unique constant suffix, so `span='thisEvent'` finds `EKSpanThisEvent`.
- Constructor kwargs reach class factories, `initWith...` initializers, and settable properties in one call: `EKEvent(eventStore=s, title=t, startDate=d)`.
- Indexed collections (`count`/`objectAtIndex:`) get `len`, indexing, lazy iteration, and an `L`-style `map`, so `first(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`](fastcocoa.md) reads Apple's Swift symbol graphs, so methods also answer to their curated Swift names, with the argument labels every Swift tutorial shows:

```python
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`](fastcocoa.md) 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?`, and `inspect.signature` show 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, and `full_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 a `PHFetchOptions`" is `sdksearch('PHFetchOptions')` and "delete a reminder" is `sdksearch('remove.*reminder')`. `kind=` filters `'im'`/`'cm'`/`'init'`/`'protocol'`/`'enum'`/`'property'`. Search never extracts a table silently; pass `frameworks=` to opt in.

The search flow, end to end:

```python
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`](fastcocoa.md#nsurl)/[`nsdate`](fastcocoa.md#nsdate)/[`pydate`](fastcocoa.md#pydate)/[`topy`](fastcocoa.md#topy) convert values by hand where needed. [`Sig`](fastcocoa.md#sig) awaits a Cocoa callback from the event loop; [`wait_cb`](fastcocoa.md#wait_cb) is its blocking twin for worker threads, with a `...` argument marking where the callback goes. [`camera`](fastcocoa.md#camera) is a running capture session as a context manager. [`fastcocoa.swifttool`](swifttool.md) 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

```python
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

```python
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

```python
def chk(
    res:tuple
):
```

*Unpack a Cocoa `(value, error)` or `(ok, error)` out-param pair, raising `RuntimeError` on failure.*

### topy

```python
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

```python
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

```python
def nsurl(
    path:str | pathlib._local.Path
):
```

*Convert a filesystem path (expanding `~`) to a file `NSURL`.*

### nsdate

```python
def nsdate(
    dt:datetime.datetime
):
```

*Convert a Python `datetime` to an `NSDate`.*

### pydate

```python
def pydate(
    d
)->datetime.datetime | None:
```

*Convert an `NSDate` (or `None`) to a local Python `datetime`.*

```python
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`](fastcocoa.md#sig) to bridge a Cocoa completion block into `asyncio`, [`wait_cb()`](fastcocoa.md#wait_cb) for the blocking equivalent on a worker thread, and [`camera()`](fastcocoa.md#camera) for a running capture session on the default camera.

### Sig

```python
def Sig():
```

*Await a Cocoa callback from the loop: pass `sig.set` (any thread or queue) and `await sig.wait(secs)`*

#### Sig.set

```python
def set():
```

*Signal waiting coroutines from any thread or dispatch queue.*

#### Sig.wait

```python
async def wait(
    secs:float, # Seconds before TimeoutError
):
```

### wait\_cb

```python
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`](fastcocoa.md#sig) for worker-thread bodies: call `f`, return the callback's args as Python values*

### camera

```python
def camera():
```

*A running capture session on the default camera, yielding its photo output*

## Browsing and searching the SDK

[`fastcocoa`](fastcocoa.md) distills Apple's Swift symbol graphs and header comments into searchable Python tables. Search never triggers extraction silently; pass `frameworks=` to opt in.

### sdkops

```python
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

```python
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

```python
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`](fastcocoa.md#full_docs) for one Markdown reference.*

### sdksearch

```python
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.*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/apisurface.py#L161)

### full\_docs

```python
def full_docs(
    groups
):
```

*Markdown overview of every group and operation in a `mk_groups` tree.*
