pycocoa

Package pycocoa |
[frames] | no frames]

# Package pycocoa

A basic, ctypes-based Python binding to the macOS Objective-C Cocoa runtime and several other macOS libraries.

This is the cocoa-python package by Phillip Nguyen (C) 2011, modified, extended, tested, documented and published with permission under both the MIT License and the original New BSD License.

# Installation

To install `pycocoa`, type `pip install pycocoa` or `easy_install pycocoa` in a terminal window. Alternatively, download `pycocoa-y.m.d.zip` from PyPI or GitHub, `unzip` the downloaded file, `cd` to directory `pycocoa-y.m.d` and type `python setup.py install`. To run the PyCocoa tests, type `python setup.py test` or `python test/run.py` before or after installation.

Examples cocoavlc.py and simple_VLCplayer.py require installation of the VLC App for macOS and the corresponding Python-VLC binding.

# Documentation

In addition to the pycocoa package, the distribution files contain several tests, some examples and the documentation (generated by Epydoc using command line `epydoc --html --no-private --no-source --name=pycocoa --url=... -v pycocoa`).

# Tests

The tests and examples have only been run with 64-bit Python 3.13.1, 3.12.7. 3.11.5 and 2.7.18 using Python-VLC 3.0.21, 3.0.18, 3.0.16, 3.0.12, 3.0.11, 3.0.10, 3.0.8, 3.0.6, 3.0.4 and 2.2.8 (with the compatible VLC App) on macOS 14.6.1 Sonoma, 13.2 Ventura, 12.0.1 Monterey, 11.6.1 and 11.5.2 Big Sur (aka 10.16), 10.15.7 Catalina, 10.14.6 Mojave or 10.13.6 High Sierra. The tests run with and without `lazy import` in Python 3.

Python 3.13.1, 3.12.7 and 3.11.5 run on Apple Silicon (`arm64` natively), other Python versions run on Intel (`x86_64`) or Intel emulation (`"arm64_x86_64"`, see function pycocoa.machine).

Previously, `pycocoa` was tested with 64-bit Python 3.10.0, 3.9.6, 3.8.6, 3.8.3, 3.8.1, 3.7.4-6, 3.6.5, 2.7.17 and macOS' 2.7.16. However, `pycocoa` has not been tested on iOS nor with 32-bit Python and does not work with PyPy nor with Intel(R) Python.

# Notes

All `pycocoa` source code has been statically checked with PyChecker, PyFlakes, PyCodeStyle (formerly Pep8) and McCabe using 64-bit Python 2.7.18 and with Flake8 using 64-bit Python 3.12.01 on macOS 14.1.2 Sonoma.

Some alternatives to `pycocoa` are (a) PyObjC, the most comprehensive Python to Objective-C bridge (no longer included in macOS' Python), (b) Rubicon-ObjC for Python 3.5+, taking advantage of Python's typing annotations, (c) PyGUI for macOS and (d) wxPython.

# Licenses

Copyright (C) 2017-2025 -- mrJean1 at Gmail -- All Rights Reserved.

`Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:`

`The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.`

`THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`

__

Copyright (C) 2011 -- Phillip Nguyen -- All Rights Reserved.

`Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:`

`1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.`

`2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.`

`3. Neither the name of objective-ctypes nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.`

`THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.`

Version: 25.01.18

Submodules
pycocoa.__main__: Print pycocoa all public attributes, pycocoa version, Python release, etc. pycocoa.apps: Types App and Tile, wrapping ObjC `NSApplication` and `NSDocktile`. pycocoa.bases: (INTERNAL) Base classes for Python `Types`. pycocoa.colors: Types Color, ColorError, CMYColor, GrayScaleColor, HSBColor, RGBColor, TintColor and UIColor wrapping Cocoa's `NSColor` and `enum`-like constants CMYColors, GrayScaleColors, HSBColors, RGBColors, TintColor, TintColors, UIColors and all Colors accessible by color space acronym like `CMY`, `GS`, `RGB`, etc. pycocoa.dicts: Types FrozenDict and Dict, wrapping ObjC `NS[Mutable]Dictionary`. pycocoa.faults: Handle uncaught `ObjC/NSExceptions` and other `fault`s similar to standard module `faulthandler` available since Python 3.3. pycocoa.fonts: Type Font, etc., wrapping ObjC `NSFont`. pycocoa.geometry: Types Point, Rect and Size, wrapping ObjC `NSPoint_t`, NSRect_t, `NSSize_t`. pycocoa.getters: `get_...` functions to obtain ObjC classes, methods, protocols, etc. pycocoa.lazily: Lazily import `pycocoa` modules and attributes, based on lazy_import from Brett Cannon's modutil. pycocoa.lists: Type List, wrapping ObjC `NSMutableArray`. pycocoa.menus: Types Item, ItemSeparator, Menu and MenuBar, wrapping ObjC `NSMenuItem` and `NSMenu` and Keys. pycocoa.nstypes: ObjC classes `NS...` and conversions from `NS...` ObjC to Python instances. pycocoa.octypes: ObjC `..._t` type definitions and some additional `ctypes`. pycocoa.oslibs: Various ObjC and macOS libraries, signatures, constants, etc. pycocoa.panels: Types OpenPanel and SavePanel, wrapping ObjC `NSOpenPanel` and `NSSavePanel`. pycocoa.printers: Types Printer, Paper, PaperCustom and PaperMargins, wrapping ObjC `NSPrinter`, `PMPrinter`, `PMPaper` respectively `PMPaperMargins` plus several `get_...` print functions. pycocoa.pytypes: Conversions from `NS...` ObjC instances to Python. pycocoa.runtime: Classes `ObjCClass`, `ObjCInstance`, `ObjCMethod`, `ObjCSubclass`, etc. pycocoa.screens: Types Frame and Screen, wrapping ObjC `NSScreen`. pycocoa.sets: Types FrozenSet and Set, wrapping ObjC `NS[Mutable]Set`. pycocoa.strs: Type Str, wrapping ObjC `NSStr[ing]`. pycocoa.tables: Types Table and TableWindow, wrapping ObjC `NSTableView`, `NSWindow`. pycocoa.tuples: Type Tuple, wrapping (immutable) ObjC `NSArray`. pycocoa.utils: Utility functions, constants, internals, etc. pycocoa.windows: Types AutoResize, Window, MediaWindow, Screen, WindowStyle, wrapping ObjC `NSWindow`, etc.

Classes
| LazyImportError Lazy import is not supported, disabled or failed some other way.
| Adict A `dict` with key and attribute access to the items and callable to add items.
| AlertPanel Python Type to show an alert, wrapping ObjC `NSAlert`.
| Allocator_t ObjC `CFAllocatorRef` type.
| App Python `App` Type, wrapping an ObjC `NSApplication`.
| Array_t
| AutoResizeError `AutoResize` option error.
| BOOL_t ObjC `boolean` type.
| Block_t ObjC `block` type.
| BrowserPanel Python Type to show a URL or file.
| BuiltInScreen The BuiltIn screen.
| CFIndex_t
| CFRange_t ObjC `struct` with fields `loc[ation]` and `len[gth]` (both `CFIndex_t`).
| CGBitmapInfo_t
| CGDirectDisplayID_t
| CGError_t
| CGFloat_t
| CGGlyph_t
| CGPoint_t ObjC `struct` with fields `x` and `y` (both `CGFloat_t`).
| CGRect_t ObjC `struct` with fields `origin` and `size` (`NSPoint_t`, `NSSize_t`).
| CGSize_t ObjC `struct` with fields `width` and `height` (both `CGFloat_t`).
| CMYColor Color in the Cyan-Magenta-Yellow space.
| CTFontOrientation_t
| CTFontSymbolicTraits_t
| Cache2 Two-level cache implemented by two `dict`s, a primary level-1 `dict` and a secondary level-2 `dict`.
| Class_t ObjC `Class` type, encoding b'#'.
| Color Base `Color` class wrapping `NSColor` objects, intended specifically to avoid fatal exceptions when accessing non-applicable `NSColor` attributes.
| ColorError `Color` issue.
| Data_t
| DeepestScreen The Deepest screen, the one with most colors.
| Dict Python `dict` Type, wrapping an ObjC `NSMutableDictionary`.
| Dictionary_t
| ErrorPanel Python Type to show an `NSError` alert, wrapping ObjC `NSAlert`.
| ExternalScreen An External screen or monitor.
| Font Python `Font` Type, wrapping ObjC `NSFont`.
| FontError Font selection error.
| FontTraitError Font traits error.
| Frame A screen frame, wrapping ObjC NSRect_t.
| FrozenDict Python immutable `dict` Type, wrapping an (immutable) ObjC `NSDictionary`.
| FrozenSet Python `frozenset` Type, wrapping an immutable ObjC `NSSet`.
| GrayScaleColor Color in the Gray-Scale space.
| HSBColor Color in thecHue-Saturation-Brightness space.
| IMP_t ObjC `IMPlementation` type.
| Id_t ObjC `Id/self` type, encoding b'@'.
| Item Python menu Item Type, wrapping ObjC `NSMenuItem`.
| ItemSeparator Python menu ItemSeparator Type, wrapping ObjC `NSMenuItem.separatorItem`.
| Ivar_t ObjC `instance variable` type.
| List Python `list` Type, wrapping an ObjC `NSMutableArray`.
| MainScreen A Main screen, the one with the menu bar, key focus, etc.
| MediaWindow Media window Python Type, wrapping ObjC `NSWindow/NSView`.
| Menu Python Menu Type, wrapping ObjC `NSMenu`.
| MenuBar Python MenuBar Type, wrapping ObjC `NSMenu`.
| Method_t ObjC `method` type.
| NSDecimal Optimized, Python `NSDecimalNumber` class.
| NSDouble_t
| NSExceptionError Python Error wrapping an `ObjC/NSException`.
| NSFloat_t
| NSInteger_t
| NSMakePoint ObjC `struct` with fields `x` and `y` (both `CGFloat_t`).
| NSMakeRange ObjC `struct` with fields `loc[ation]` and `len[gth]` (both `NSUInteger_t`).
| NSMakeRect ObjC `struct`, like NSRect_t with different signature and properties.
| NSMakeSize ObjC `struct` with fields `width` and `height` (both `CGFloat_t`).
| NSPoint_t ObjC `struct` with fields `x` and `y` (both `CGFloat_t`).
| NSRange_t ObjC `struct` with fields `loc[ation]` and `len[gth]` (both `NSUInteger_t`).
| NSRect4_t ObjC `struct`, like NSRect_t with different signature and properties.
| NSRect_t ObjC `struct` with fields `origin` and `size` (`NSPoint_t`, `NSSize_t`).
| NSSize_t ObjC `struct` with fields `width` and `height` (both `CGFloat_t`).
| NSStr Python wrapper for the ObjC `NS[Constant]String`.
| NSTimeInterval_t
| NSUInteger_t
| NumberType_t
| Number_t
| ObjCBoundClassMethod Python wrapper for a bound ObjC class method, only to distinguish bound class from bound instance methods.
| ObjCBoundMethod Python wrapper for a bound ObjC instance method, an IMP_t.
| ObjCClass Python wrapper for an ObjC class.
| ObjCClassMethod Python class representing an unbound ObjC class method, only to distinguish class methods from instance methods.
| ObjCConstant Python wrapper for an ObjC constant.
| ObjCDelegate Register the `_NS_Delegate._ObjC` (sub)class and create an ObjCClass`(_NS_Delegate.__name__)`.
| ObjCInstance Python wrapper for an ObjC instance.
| ObjCMethod Python class representing an unbound ObjC instance method, actually an IMP_t.
| ObjCSubclass Python class creating an ObjC sub-class of an existing ObjC (super)class.
| ObjC_t Base type to pretty-print ctypes `c_void_p`.
| OpenPanel Python Type to select a file, wrapping ObjC `NSOpenPanel`.
| OptionFlags_t
| Paper Python `Paper` Type, wrapping an opaque ObjC `PMPaper`.
| PaperCustom Create a custom Paper.
| PaperMargins Python `PaperMargins` Type, wrapping an ObjC `PMPaperMargins`.
| Point Python Type, wrapping an ObjC `NSPoint_t`.
| Point2 Python Type, like Point, different signature.
| Printer Python `Printer` Type, wrapping ObjC `NSPrinter` and `PMPrinter`.
| Protocol_t ObjC `protocol` type.
| RGBColor Color in the Red-Green-Blue space.
| Rect Python Type, wrapping an ObjC NSRect_t.
| Rect4 Python Type, like Rect, but signature as ObjC NSRect4_t.
| RunLoop_t ObjC `CFRunLoopRef` type.
| SEL_t ObjC `SELector/cmd` type, encoding `b':'`.
| SavePanel Python Type to save a file, wrapping ObjC `NSSavePanel`.
| Screen Screen Python Type, wrapping ObjC NSRect_t.
| Set Python `set` Type, wrapping an ObjC `NSMutableSet`.
| Set_t
| Size Python Type, wrapping an ObjC `NSSize_t`.
| Size2 Python Type, like Size, different signature.
| Str Python `str` Type, wrapping (immutable) ObjC `NSStr[ing]`.
| StrAttd Python `str` Type, wrapping (immutable) ObjC `NSAttributedString`.
| String_t
| Struct_t ObjC `struct` type.
| Table Python rows and columns {Table} Type, wrapping an ObjC `NSTableView`.
| TableWindow Python Type for a vertically scrollable window, wrapping ObjC `NSWindow/NSScrollView`.
| TextPanel Scrollable text panel Python Type, wrapping ObjC `NSAlert`.
| TextWindow Scrollable text window Python Type, wrapping ObjC `NSWindow/NSView`.
| Tile Dock tile for an App, wrapping an ObjC `NSDockTile`.
| TimeInterval_t
| TintColor Dynamic color, adaptable to vibrancy and accessibility settings.
| Tuple Python `tuple` Type, wrapping an immutable ObjC `NSArray`.
| TypeCodeError Error in ObjC type encoding.
| TypeID_t
| TypeRef_t ObjC opaque type.
| UIColor Dynamic color for User-Interface elements, adaptable to vibrancy and accessibility settings.
| URL_t ObjC `URL` type.
| UniChar_t
| Union_t ObjC `union` type.
| UnknownPtr_t Unknown pointer.
| Unknown_t Unknown type.
| VoidPtr_t Same as `c_void_p`, but distinguishable from `c_void_p`.
| Window Basic window Python Type, wrapping ObjC `NSWindow`.
| WindowError Window error.
| WindowStyleError Window style error.
| at Acronym NSStr.
| c_ptrdiff_t
| c_struct_t Base type to pretty-print ctypes `Structures`.
| module_property_RO Decorator for a `Read-Only` module property.
| objc_method_description_t ObjC `struct` with fields `name` and `types` (`SEL_t`, `c_char_p`).
| objc_property_attribute_t ObjC `struct` with fields `name` and `value` (both `c_char_p`).
| objc_property_t ObjC `property` Class.
| objc_super_t ObjC `struct` with fields `receiver` and `class` (`Id_t`, `Class_t`).
| unichar_t

Functions
None2NS(py) Return the `NSNull` singleton for Python's `None`. |
SIGs_enabled(*sigs) Return the signals currently handled as `fault`. |
add_ivar(clas, name, ctype) Add an instance variable to an ObjC class, |
add_method(clas, name_, method, encoding) Add a method to an ObjC class. |
add_protocol(clas, protocol) Add a protocol to an ObjC class. |
add_subclass(superclas, name, register=False) Create a new sub-class of the given super-class. |
app_title(title) Get/set the app title. |
aspect_ratio(width, *height, **Error_kwds) Compute the smallest, integer aspect ratio. |
autoResizes(*options) Return a combination of auto resize options, specified by name. |
bool2NS(py) Create an `NSBoolean` instance from a Python `bool`. |
bytes2NS(py) Create an `NSData` instance from Python `bytes`. |
bytes2repr(bytestr) Represent `bytes` or `str` as `b"..."`. |
bytes2str(bytestr, dflt=missing, name='') Convert `bytes`/`unicode` to `str` if needed. |
clipstr(bytestr, limit=50) Clip a string to the given length limit. |
closeTables() Close all tables. |
dict2NS(py, frozen=False) Create an `NS[Mutable]Dictionary` instance from a Python `dict`. |
disable() Disable `fault` handling and uninstall the signal handlers installed by faults.enable, like the faulthandler module in Python 3.3 and later. |
drain(objc) Release all objects in an `NSAutoreleasePool` instance. |
enable(file=_sys.stdout, **unused) Enable `fault` handling similar to the faulthandler module available in Python 3.3 and later. |
exiting(status=None) Get/set the `exit` and `status` to use after `fault`s or uncaught `ObjC/NSException`s. |
flint(f) Return `int` for integer `float`. |
float2NS(py) Create an `NSNumber` instance from a Python `float` or `int`. |
fontTraits(*traits) Return a font traits mask for the named traits. |
fontTraitstrs(traits) Return font traits as names. |
fontfamilies(*prefixes) Yield the installed font families. |
fontnamesof(family) Yield the available font names of a family. |
fontsof(family, size=0, weight=None) Yield the available fonts of a family. |
fontsof4(family) Yield the available fonts of a family. |
frozenset2NS(py) Create an (immutable) `NSSet` instance from a Python `frozenset`. |
gcd(a, b) Calculate the Greatest Common Divisor of a and b. |
generator2NS(py) Create an `NSArray` instance from a Python `generator`. |
getUncaughtExceptionHandler() Get the currently installed uncaught `ObjC/NSException` handler. |
get_c_func_t(encoding, codes=None) Get the `ctypes` function type for a given function signature. |
get_class(name) Get a registered ObjC class by name. |
get_classes(*prefixes) Yield all loaded ObjC classes with a name starting with one of the given prefixes. |
get_classname(clas, dflt=missing) Get the name of an ObjC class. |
get_classnameof(objc, dflt=missing) Get the name of the ObjC class of an object. |
get_classof(objc) Get the ObjC class of an object. |
get_inheritance(clas) Yield the inheritance of an ObjC class. |
get_ivar(objc, name, ctype=None) Get the value of an instance variable (ivar). |
get_ivars(clas, *prefixes) Yield all instance variables (ivar) of an ObjC class with a name starting with one of the given prefixes. |
get_lib(name) Find and load a `.dylib` library. |
get_libPC() Get the `PrintCore` framework library. |
get_lib_framework(name, services=`'``ApplicationServices``'`, version='') Load a `Frameworks services .framework` library. |
get_libs() Return the `.dylib` libraries loaded so far. |
get_metaclass(name) Get a registered ObjC metaclass by name. |
get_method(clas, name) Get a method of an ObjC class by name. |
get_methods(clas, *prefixes) Yield all methods of an ObjC class with a name starting with one of the given prefixes. |
get_papers(*printers) Yield the papers available at the given printer(s). |
get_printer(*prefixes) Find a printer by name or by ID or get the default printer. |
get_printer_browser(server=None) Show the printer browser for the given server. |
get_printers(server=None) Yield all printers available at the given server. |
get_properties(clas_or_proto, *prefixes) Yield all properties of an ObjC class or protocol with a name starting with one of the given prefixes. |
get_protocol(name) Get a registered ObjC protocol by name. |
get_protocols(clas, *prefixes) Yield all protocols of an ObjC class with a name starting with one of the given prefixes. |
get_resolutions(*printers) Yield the resolutions supported by the given printer(s). |
get_selector(name_) Get an ObjC selector by name. |
get_selectorname_permutations(name_, leading=False) Yield all permutations of a Python-style selector name. |
get_selectornameof(sel) Get the name of an ObjC selector. |
get_superclass(clas) Get the ObjC super-class of an ObjC class. |
get_superclassnameof(objc, dflt=missing) Get the name of the ObjC super-class of an object. |
get_superclassof(objc) Get the ObjC super-class of an object. |
inst2strepr(inst, strepr, *attrs) Convert an instance's attributes, maintaining the order. |
int2NS(py) Create an `NSNumber` instance from a Python `int` or `long`. |
isAlias(path) Resolve a macOS file or folder alias. |
isClass(objc) Check whether an object is an ObjC clas. |
isImmutable(objc, mutableClass, immutableClass, name=`'``ns``'`) Check that an ObjC object is an instance of the immutable class. |
isLink(path) Resolve a file or folder link or alias. |
isMetaClass(objc) Check whether an object is an ObjC metaclass. |
isNone(obj) Return True if obj is `None, NSMain.nil, NSMain.Null`, etc. |
isObjCInstanceOf(objc, *Classes, **name_missing) Check whether an ObjC object is an instance of some ObjC class. |
is_enabled(sig=None) Check whether `fault` handling is enabled, similar to the faulthandler module available in Python 3.3 and later. |
isinstanceOf(inst, *classes, **name_missing) Check a Python instance' class. |
iterator |
iterbytes(collection) iter(callable, sentinel) -> iterator |
lambda1(arg) Inlieu of using lambda arg: arg. |
leaked2() Return the number of memory leaks. |
list2NS(py) Create an `NSMutableArray` instance from a Python `list`. |
logf(fmt, *args, **kwds) Formatted log fmt % args with optional keywords. |
machine() Return the `platform.machine` string, distinguishing Intel from emulating Intel on Apple Silicon (on macOS). |
map2NS(py) Create an `NSArray` instance from a Python `map`. |
name2objc(name_) Convert a (selector) name to `bytes` and ObjC naming rules. |
name2py(name_) Convert a (selector) name `str` and Python naming conventions. |
name2pymethod(name_) Convert a (selector) name to a valid Python callback method. |
ns2App(ns) Get the App instance from an `NSApplication` or an `NSNotification` instance. |
ns2Item(ns) Get the Python instance for an `NSMenuItem`. |
ns2Type(ns) Convert an `NS...` ObjC object to an instance of the corresponding Python Type and value. |
ns2TypeID2(ns, dflt=None) Get the `NS...` ObjC `TypeID`. |
ns2Window(ns) Get the Window instance for an ObjC `NSWindow` or `NSNotification` instance. |
ns2py(ns, dflt=missing) Convert (an instance of) an ObjC class to an instance of the equivalent Python standard type or wrapper and value. |
nsArray2listuple(ns, ctype=<class 'ctypes.c_void_p'>) Create a Python `list` or `tuple` from an `NS[Mutable]Array`. |
nsArray2tuple(ns, ctype=<class 'pycocoa.runtime.ObjCInstance'>) Create a Python `tuple` from an immutable `NSArray`. |
nsBoolean2bool(ns, dflt=missing) Create a Python `bool` from an `NSBoolean`. |
nsBundleRename(ns_title, match=`'``Python``'`) Change the bundle title if the current title matches. |
nsData2bytes(ns, dflt=`'````'`) Create Python `bytes` from `NSData`. |
nsDecimal2decimal(ns) Create a Python `Decimal` from an `NSDecimalNumber`. |
nsDescription2dict(ns, **defaults) Create an immutable `dict` object with key and attribute access to items by name. |
nsDictionary2dict(ns, ctype_keys=<class 'ctypes.c_void_p'>, ctype_vals=<class 'ctypes.c_void_p'>) Create a Python `dict` from an `NS[Mutable]Dictionary`. |
nsDictionary2items(ns) Yield the `(key, value)` items from an `NSDictionary`. |
nsException(name=None, reason=`'``not given``'`, **info) Create an `ObjC/NSException` instance. |
nsIter(ns, reverse=False) Iterate over an `NS..` ObjC objects's (reverse) enumerator. |
nsIter2(ns, reverse=False) Iterate over an `NS..` ObjC objects's (reverse) enumerator. |
nsLog(ns_fmt, *ns_args) Formatted ObjC write to the console. |
nsLogf(fmt, *args) Formatted write to the console. |
nsNull2none(ns) Return Python `None` for an `NS/CFNull` or `nil`. |
nsNumber2num(ns, dflt=missing) Create a Python `Decimal`, `int` or `float` from an `NSNumber`. |
nsOf(inst) Return the `.NS` ObjC object of a Python wrapper or Type instance. |
nsRaise(name=None, reason=`'``not given``'`, **info) Create an `NSException` and mimick `@throw NSException`. |
nsSet2set(ns, ctype=<class 'ctypes.c_void_p'>) Create a Python `set` or `frozenset` from an `NS[Mutable]Set`. |
nsString2str(ns, dflt=None) Create a Python `str` or `unicode` from an `NS[Mutable]Str[ing]`. |
nsTextSize3(text, ns_font=None) Return the size of a multi-line text. |
nsTextView(text, ns_font) Return an `NSTextView` for the given text string. |
nsThrow(nsExc) Mimick ObjC's `@throw NSException` to raise an exception. |
nsURL2str(ns) Create a Python `str` from `NSURL` string. |
nsValue2py(ns, dflt=missing) Create a Python instance from an `NS[Concrete]Value`. |
printf(fmt, *args, **kwds) Formatted print fmt % args with optional keywords. |
properties(inst) All property names and values. |
property2(inst, name) Return the property `get` and `set` method. |
property_RO(method) Decorator for `Read_Only` class/instance property. |
py2NS(py) Convert (an instance of) a Python object into an instance of the equivalent `NS...` ObjC class: |
range2NS(py) Create an `NSArray` instance from a Python `range`. |
register_subclass(subclas) Register an ObjC sub-class. |
release(objc) Release an ObjC instance to be deleted, eventually. |
retain(objc) Preserve an ObjC instance from destruction. |
send_message(objc, sel_name_, *args, **resargtypes) Send message to an ObjC object. |
send_super(objc, sel_name_, *args, **resargtypes) Send message to the super-class of an ObjC object. |
send_super_init(objc) Send 'init' message to the super-class of an ObjC object. |
set2NS(py) Create an `NSMutableSet` instance from a Python `set`. |
setUncaughtExceptionHandler(handler, log=True, raiser=False) Install a callback to handle uncaught `ObjC/NSException`s. |
set_ivar(objc, name, value, ctype=None) Set an instance variable of an ObjC object. |
sortuples(iterable) Sort tuples alphabetically, case-insensitive. |
split_emcoding2(encoding, start=0) Split the type encoding of a method signature into separate, single encodings and the combined encoding. |
split_encoding(encoding) Split a type encoding into separate type encodings. |
str2NS(py) Create an `NSStr` instance from a Python `str`. |
str2bytes(bytestr, dflt=missing, name='') Convert `str` to `bytes`/`unicode` if needed. |
terminating(app, timeout=None) Set up a separate thread to terminate an NSApplication by calling the `.terminate_` method after the given timeout has elapsed. |
time2NS(py=None, since=1970) Create an `NSDate` instance from a timestamp. |
title2action(title) Convert a menu item `title` to a Python callback method name. |
tuple2NS(py) Create an immutable `NSArray` instance from a Python `tuple`. |
type2NS(py) Create the `NS...` ObjC object for a Python Type or wrapper instance. |
type2strepr(inst, strepr=<type 'str'>, **kwds) Represent a Python Type instance as `str` or `repr`. |
unicode2NS(py) Create an `NSStr` instance from a Python `unicode` string. |
url2NS(py, url2=None) Create an `NSURL` instance from a Python string. |
windowStyles(*styles) Return a combination of window styles, specified by name. |
z1000str(size, sep='_') Convert a size to string with 1_000's seperator. |
zSIstr(size, B=`'``B``'`, K=1024) Convert a size to string with SI-units suffix. |
zfstr(flt, prec=3) Format a `float` and strip trailing zero decimals. |

Variables
| pycocoa_abspath = ``'``/Users/jean/Library/CloudStorage/Dropbox/Pr``...``
| version = ``'``25.1.18``'``
| AlertStyle = `AlertStyle.Critical`...``
| AutoResize = `AutoResize.HeightSizable=1<`...``
| BezelStyle = `BezelStyle.Disclosure`...``
| Border = `Border.Bezel`...``
| CGImageEncoding = ``'``{CGImage=}``'``
| CGPointEncoding = ``'``{CGPoint=dd}``'``
| CGRectEncoding = ``'``{CGRect={CGPoint=dd}{CGSize=dd}}``'``
| CGSizeEncoding = ``'``{CGSize=dd}``'``
| CMYColors = `CMYColors.Cyan=CMYColor(_NSTaggedPointerColor, nam`...``
| Colors = `Colors.CMY=CMYColo`...``
| DEFAULT_UNICODE = ``'``utf-8``'``
| FontTrait = `FontTrait.Bold`...``
| Fonts = `Fonts.App=Font({family='Helvetica', name='Helvetica', `...``
| GrayScaleColors = `GrayScaleColors.Black=GrayScaleColor(_NSTagg`...``
| HSBColors = `HSBColors.NoneYet=None`
| Keys = `Keys.ACK=0`...``
| Libs = `Libs.AppKit=<CDLL 'AppKit.framework/AppKit', handle 7ff`...``
| NO = `False`
| NSAcknowledgeCharacter = `6`
| NSAlert = `ObjCClass('NSAlert')`
| NSAlphaShiftKeyMask = `65536`
| NSAlternateKeyMask = `524288`
| NSAnyEventMask = `4294967295`
| NSApplication = `ObjCClass('NSApplication')`
| NSApplicationActivationPolicyAccessory = `1`
| NSApplicationActivationPolicyProhibited = `2`
| NSApplicationActivationPolicyRegular = `0`
| NSApplicationDefined = `15`
| NSApplicationDelegate = `<pycocoa.utils.module_property_RO obje`...``
| NSApplicationDidHideNotification = `c_void_p(140704555838160)`
| NSApplicationDidUnhideNotification = `c_void_p(140704555838256)`
| NSApplicationPresentationDefault = `0`
| NSApplicationPresentationDisableHideApplication = `256`
| NSApplicationPresentationDisableProcessSwitching = `32`
| NSApplicationPresentationHideDock = `2`
| NSApplicationPresentationHideMenuBar = `8`
| NSArray = `ObjCClass('NSArray')`
| NSAttributedString = `ObjCClass('NSAttributedString')`
| NSAutoreleasePool = `ObjCClass('NSAutoreleasePool')`
| NSBackSpaceCharacter = `8`
| NSBackTabCharacter = `25`
| NSBackingStoreBuffered = `2`
| NSBackingStoreNonretained = `1`
| NSBackingStoreRetained = `0`
| NSBellCharacter = `7`
| NSBezierPath = `ObjCClass('NSBezierPath')`
| NSBoolean = `NSNumber.numberWithBool_`
| NSBundle = `ObjCClass('NSBundle')`
| NSCancelButton = `0`
| NSCancelCharacter = `24`
| NSCarriageReturnCharacter = `13`
| NSCenterTextAlignment = `2`
| NSClearLineFunctionKey = `63289`
| NSColor = `ObjCClass('NSColor')`
| NSCommandKeyMask = `1048576`
| NSConcreteNotification = `ObjCClass('NSConcreteNotification')`
| NSConcreteValue = `ObjCClass('NSConcreteValue')`
| NSConstantString = `ObjCClass('NSConstantString')`
| NSControlKeyMask = `262144`
| NSData = `ObjCClass('NSData')`
| NSDataLineEscapeCharacter = `16`
| NSDate = `ObjCClass('NSDate')`
| NSDecimalNumber = `ObjCClass('NSDecimalNumber')`
| NSDefaultRunLoopMode = `RunLoop_t.in_dll(libAppKit, 'NSDefaultR`...``
| NSDeleteCharacter = `127`
| NSDeleteFunctionKey = `63272`
| NSDeviceControl1Character = `17`
| NSDeviceControl2Character = `18`
| NSDeviceControl3Character = `19`
| NSDeviceControl4Character = `20`
| NSDictionary = `ObjCClass('NSDictionary')`
| NSDockTile = `ObjCClass('NSDockTile')`
| NSDouble = `NSNumber.numberWithDouble_`
| NSDownArrowFunctionKey = `63233`
| NSEndFunctionKey = `63275`
| NSEndOfMediumCharacter = `25`
| NSEndOfTextCharacter = `3`
| NSEndOfTransmitBlockCharacter = `23`
| NSEndOfTransmitCharacter = `4`
| NSEnquiryCharacter = `5`
| NSEnterCharacter = `3`
| NSEnumerator = `ObjCClass('NSEnumerator')`
| NSError = `ObjCClass('NSError')`
| NSEscapeCharacter = `27`
| NSEventTrackingRunLoopMode = `RunLoop_t.in_dll(libAppKit, 'NSEv`...``
| NSException = `ObjCClass('NSException')`
| NSF19FunctionKey = `63254`
| NSF1FunctionKey = `63236`
| NSFileHandlingPanelCancelButton = `0`
| NSFileHandlingPanelOKButton = `1`
| NSFileSeparatorCharacter = `28`
| NSFlagsChanged = `12`
| NSFloat = `NSNumber.numberWithDouble_`
| NSFloatEncoding = ``'``f``'``
| NSFont = `ObjCClass('NSFont')`
| NSFontBoldMask = `2`
| NSFontClarendonSerifsClass = `1073741824`
| NSFontClassMask = `4026531840`
| NSFontColorGlyphsMask = `8192`
| NSFontCompositeMask = `16384`
| NSFontCompressedMask = `512`
| NSFontCondensedMask = `64`
| NSFontDescriptor = `ObjCClass('NSFontDescriptor')`
| NSFontExpandedMask = `32`
| NSFontFreeformSerifsClass = `1879048192`
| NSFontItalicMask = `1`
| NSFontManager = `ObjCClass('NSFontManager')`
| NSFontModernSerifsClass = `805306368`
| NSFontMonoSpaceMask = `1024`
| NSFontNarrowMask = `16`
| NSFontNonStandardCharacterSetMask = `8`
| NSFontOldStyleSerifsClass = `268435456`
| NSFontOrnamentalsClass = `2415919104`
| NSFontPanel = `ObjCClass('NSFontPanel')`
| NSFontPosterMask = `256`
| NSFontSansSerifClass = `2147483648`
| NSFontScriptsClass = `2684354560`
| NSFontSlabSerifsClass = `1342177280`
| NSFontSmallCapsMask = `128`
| NSFontSymbolicClass = `3221225472`
| NSFontTransitionalSerifsClass = `536870912`
| NSFontUIOptimizedMask = `4096`
| NSFontUnboldMask = `4`
| NSFontUnitalicMask = `16777216`
| NSFontUnknownClass = `0`
| NSFontVerticalMask = `2048`
| NSFormFeedCharacter = `12`
| NSFunctionKeyMask = `8388608`
| NSGroupSeparatorCharacter = `29`
| NSHelpFunctionKey = `63302`
| NSHelpKeyMask = `4194304`
| NSHomeFunctionKey = `63273`
| NSHorizontalTabCharacter = `9`
| NSImage = `ObjCClass('NSImage')`
| NSImageView = `ObjCClass('NSImageView')`
| NSInt = `NSNumber.numberWithInt_`
| NSIntegerEncoding = ``'``l``'``
| NSIntegerMax = `9223372036854775807`
| NSJustifiedTextAlignment = `3`
| NSKeyDown = `10`
| NSKeyUp = `11`
| NSLayoutManager = `ObjCClass('NSLayoutManager')`
| NSLeftArrowFunctionKey = `63234`
| NSLeftTextAlignment = `0`
| NSLineFeedCharacter = `10`
| NSLineSeparatorCharacter = `8232`
| NSLong = `NSNumber.numberWithLong_`
| NSLongLong = `NSNumber.numberWithLongLong_`
| NSMain = `NSMain.Application=NSApplication(<Id_t at 0x7fd608a86`...``
| NSMenu = `ObjCClass('NSMenu')`
| NSMenuItem = `ObjCClass('NSMenuItem')`
| NSMutableArray = `ObjCClass('NSMutableArray')`
| NSMutableData = `ObjCClass('NSMutableData')`
| NSMutableDictionary = `ObjCClass('NSMutableDictionary')`
| NSMutableSet = `ObjCClass('NSMutableSet')`
| NSMutableString = `ObjCClass('NSMutableString')`
| NSNaturalTextAlignment = `4`
| NSNegativeAcknowledgeCharacter = `21`
| NSNewLineCharacter = `10`
| NSNotFound = `9223372036854775807`
| NSNotification = `ObjCClass('NSNotification')`
| NSNotificationCenter = `ObjCClass('NSNotificationCenter')`
| NSNull = `ObjCClass('NSNull')`
| NSNullCharacter = `0`
| NSNumber = `ObjCClass('NSNumber')`
| NSNumericPadKeyMask = `2097152`
| NSOKButton = `1`
| NSObject = `ObjCClass('NSObject')`
| NSOpenPanel = `ObjCClass('NSOpenPanel')`
| NSPageDownFunctionKey = `63277`
| NSPageLayout = `ObjCClass('NSPageLayout')`
| NSPageUpFunctionKey = `63276`
| NSParagraphSeparatorCharacter = `8233`
| NSPointEncoding = ``'``{CGPoint=dd}``'``
| NSPointZero = `NSPoint_t(0, 0)`
| NSPrintInfo = `ObjCClass('NSPrintInfo')`
| NSPrintOperation = `ObjCClass('NSPrintOperation')`
| NSPrintPanel = `ObjCClass('NSPrintPanel')`
| NSPrinter = `ObjCClass('NSPrinter')`
| NSRangeEncoding = ``'``{_NSRange=QQ}``'``
| NSRecordSeparatorCharacter = `30`
| NSRectEncoding = ``'``{CGRect={CGPoint=dd}{CGSize=dd}}``'``
| NSRightArrowFunctionKey = `63235`
| NSRightTextAlignment = `1`
| NSSavePanel = `ObjCClass('NSSavePanel')`
| NSScreen = `ObjCClass('NSScreen')`
| NSScrollView = `ObjCClass('NSScrollView')`
| NSSet = `ObjCClass('NSSet')`
| NSShiftInCharacter = `15`
| NSShiftKeyMask = `131072`
| NSShiftOutCharacter = `14`
| NSSizeEncoding = ``'``{CGSize=dd}``'``
| NSSpaceCharacter = `32`
| NSSquareStatusItemLength = `-2`
| NSStartOfHeadingCharacter = `1`
| NSStartOfTextCharacter = `2`
| NSStatusBar = `ObjCClass('NSStatusBar')`
| NSString = `ObjCClass('NSString')`
| NSSubstituteCharacter = `26`
| NSSynchronousIdleCharacter = `22`
| NSTabCharacter = `9`
| NSTableColumn = `ObjCClass('NSTableColumn')`
| NSTableView = `ObjCClass('NSTableView')`
| NSTableViewDashedHorizontalGridLineMask = `8`
| NSTableViewDelegate = `<pycocoa.utils.module_property_RO object`...``
| NSTableViewGridNone = `0`
| NSTableViewSolidHorizontalGridLineMask = `2`
| NSTableViewSolidVerticalGridLineMask = `1`
| NSTextAlignmentCenter = `2`
| NSTextAlignmentJustified = `3`
| NSTextAlignmentLeft = `0`
| NSTextAlignmentNatural = `4`
| NSTextAlignmentRight = `1`
| NSTextField = `ObjCClass('NSTextField')`
| NSTextView = `ObjCClass('NSTextView')`
| NSTextWritingDirectionEmbedding = `0`
| NSTextWritingDirectionOverride = `2`
| NSThread = `ObjCClass('NSThread')`
| NSTrackingActiveInActiveApp = `64`
| NSTrackingCursorUpdate = `4`
| NSTrackingMouseEnteredAndExited = `1`
| NSTrackingMouseMoved = `2`
| NSUIntegerEncoding = ``'``L``'``
| NSURL = `ObjCClass('NSURL')`
| NSUnitSeparatorCharacter = `31`
| NSUpArrowFunctionKey = `63232`
| NSValue = `ObjCClass('NSValue')`
| NSVariableStatusItemLength = `-1`
| NSVerticalTabCharacter = `11`
| NSView = `ObjCClass('NSView')`
| NSWindow = `ObjCClass('NSWindow')`
| NSWindowCloseButton = `0`
| NSWindowDelegate = `<pycocoa.utils.module_property_RO object at`...``
| NSWindowDocumentIconButton = `4`
| NSWindowMiniaturizeButton = `1`
| NSWindowStyleMaskClosable = `2`
| NSWindowStyleMaskMiniaturizable = `4`
| NSWindowStyleMaskResizable = `8`
| NSWindowStyleMaskTitled = `1`
| NSWindowStyleMaskUsual = `15`
| NSWindowStyleMaskUtilityWindow = `16`
| NSWindowToolbarButton = `3`
| NSWindowZoomButton = `2`
| NSZoneEncoding = ``'``{_NSZone=}``'``
| OBJC_ASSOCIATION_ASSIGN = `0`
| OBJC_ASSOCIATION_COPY = `771`
| OBJC_ASSOCIATION_COPY_NONATOMIC = `3`
| OBJC_ASSOCIATION_RETAIN = `769`
| OBJC_ASSOCIATION_RETAIN_NONATOMIC = `1`
| PanelButton = `PanelButton.Cancel`...``
| PyObjectEncoding = ``'``{PyObject=@}``'``
| RGBColors = `RGBColors.Blue=RGBColor(_NSTaggedPointerColor, nam`...``
| Screens = `(BuiltInScreen(NSScreen, name='BuiltIn'), ExternalSc`...``
| TintColors = `TintColors.Blue=TintColor(NSDynamicSystemColor, n`...``
| UIColors = `UIColors.Control=UIColor(NSDynamicSystemColor, name`...``
| WindowStyle = `WindowStyle.Closable`...``
| YES = `True`
| c_void = `None` hash(x)
| isLazy = `None` hash(x)
| libAppKit = `<CDLL 'AppKit.framework/AppKit', handle 7fff95603c`...``
| libCF = `<CDLL 'CoreFoundation.framework/CoreFoundation', handl`...``
| libCG = `<CDLL 'CoreGraphics.framework/CoreGraphics', handle 7f`...``
| libCT = `<CDLL 'CoreText.framework/CoreText', handle 7fff956002`...``
| libFoundation = `<CDLL 'Foundation.framework/Foundation', handl`...``
| libPC = `None` hash(x)
| libobjc = `<CDLL 'libobjc.dylib', handle 7fff95605e4c at 7fd608`...``
| missing = `missing`

Function Details

### None2NS(py) |
Return the `NSNull` singleton for Python's `None`. Parameters: `py` - The value (`None`). Returns: The singleton (`NSNull`). Raises: `ValueError` - If py is not `None`.

### SIGs_enabled(*sigs) |
Return the signals currently handled as `fault`. Returns: An Adict with the `SIG*` name and value of the currently handled signals, if any.

### add_ivar(clas, name, ctype) |
Add an instance variable to an ObjC class, Parameters: `clas` - Class to add the ivar to (`ObjCClass/Subclass`). `name` - Name of the ivar (`str`). `ctype` - The ivar type code (`ctypes` or `encoding`). Returns: True if the ivar was added, False otherwise. Raises: `TypeCodeError` - Invalid ctype. Note: The ctype must be a `ctypes` type or a valid ObjC type encoding. See Also: The `_NSDeallocObserver` below.

### add_method(clas, name_, method, encoding) |
Add a method to an ObjC class. Parameters: `clas` - Class to add the method to (`ObjCClass/Subclass`). `name_` - Selector name (`str`). `method` - Decorated class or instance method (`callable`). `encoding` - Method signature (`encoding`). Returns: The method (IMP_t) if added, `None` otherwise. Raises: `TypeError` - If method is not a Python callable.

### add_protocol(clas, protocol) |
Add a protocol to an ObjC class. Parameters: `clas` - Class to add the protocol to (`ObjCClass/Subclass`). `protocol` - The `protocol` to add (`str` or Protocol_t instance). Returns: The protocol (Protocol_t) if added, `None` otherwise.

### add_subclass(superclas, name, register=False) |
Create a new sub-class of the given super-class. Parameters: `superclas` - The parent class (`str` or `Object`). `name` - The name of the sub-class (`str`). `register` - Optionally, register the new sub-class (bool). Returns: The sub-class (`Class_t`) if added, `None` otherwise. Note: After calling `add_subclass`, you MUST register the new sub-class with register_subclass, before using the new sub-class. New methods can be added after the sub-class has been registered, but any `ivar`s must be added BEFORE the class is registrated.

### app_title(title) |
Get/set the app title. Parameters: `title` - New title (`str`). Returns: Previous title (`str`).

### aspect_ratio(width, *height, **Error_kwds) |
Compute the smallest, integer aspect ratio. Parameters: `width` - The width (`float`, `int`, Size, 2-tuple (width, height), str("w:h") or `NSSize_t`). `height` - The height (`float` or `int`). Returns: 2-Tuple (width, height) as (`int`, `int`) or `None`. Example:
    >>> aspect_ratio(10, 15)
    (2, 3)
    >>> aspect_ratio(10.0, 15)
    (2, 3)
    >>> aspect_ratio(10, -15)
    (-2, 3)
    >>> aspect_ratio(-10, -15)
    (2, 3)
    >>> aspect_ratio(10.5, 15)
    (7, 10)
    >>> aspect_ratio(0, 15)
    ()

### autoResizes(*options) |
Return a combination of auto resize options, specified by name. Parameters: `options` - Option names (all positional), case-insensitive. Returns: Combined options (AutoResizes `mask`). Raises: `AutoResizeError` - One or more options are invalid.

### bool2NS(py) |
Create an `NSBoolean` instance from a Python `bool`. Parameters: `py` - The value (`int` or `bool`). Returns: The `NSMain.BooleanYES` or `.BooleanNO` singleton (`NSBoolean`).

### bytes2NS(py) |
Create an `NSData` instance from Python `bytes`. Parameters: `py` - The value (`bytes`). Returns: The ObjC instance (`NSData`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### bytes2repr(bytestr) |
Represent `bytes` or `str` as `b"..."`. Parameters: `bytestr` - `bytes` or `str`.. Returns: Representation `b'...'` (`str`).

### bytes2str(bytestr, dflt=missing, name='') |
Convert `bytes`/`unicode` to `str` if needed. Parameters: `bytestr` - `bytes`, `str` or `unicode`. `dflt` - Optional, default return value. `name` - Optional name of bytestr argument. Returns: `str` or dflt. Raises: `TypeError` - If neither `str` nor `bytes`, but only if no dflt is provided.

### clipstr(bytestr, limit=50) |
Clip a string to the given length limit. Parameters: `bytestr` - String (`bytes` or `str`). `limit` - Length limit (`int`). Returns: Clipped `bytes` or `str`.

### dict2NS(py, frozen=False) |
Create an `NS[Mutable]Dictionary` instance from a Python `dict`. Parameters: `py` - The value (`dict`). `frozen` - Immutable (`bool`), mutable otherwise. Returns: The ObjC instance (`NSDictionary` or `NSMutableDictionary`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### disable() |
Disable `fault` handling and uninstall the signal handlers installed by faults.enable, like the faulthandler module in Python 3.3 and later. Returns: `None`.

### drain(objc) |
Release all objects in an `NSAutoreleasePool` instance. Returns: The number og `ObjC` objects cleared. Note: `NSAutoreleasePool.drain` invokes the `dealloc` method only for the pool itself, not for any of the objects held/allocated in the pool.

### enable(file=_sys.stdout, **unused) |
Enable `fault` handling similar to the faulthandler module available in Python 3.3 and later. Try to install handlers for the `SIGABRT`, `SIGBUS`, `SIGFPE`, `SIGILL` and `SIGSEGV` signals to dump a an ObjC call stack and Python traceback to `file`. Raises: `TypeError` - File `file` doesn't have callable `write` and `flush` attributes. See Also: `NSMain.stdlog`.

### exiting(status=None) |
Get/set the `exit` and `status` to use after `fault`s or uncaught `ObjC/NSException`s. Parameters: `status` - The exit "door" and status code to be used (`small int`) or `None` to leave unchanged. A negative `status` invokes `os._exit(abs(status))` to terminate without normal exit processing, while a non-negative `status` uses `sys.exit(status)` after a `fault`. Returns: The previously set `exiting` code (`int`). Note: The `faulthandler` module in Python 3.3 and later ignores all `exiting` settings.

### float2NS(py) |
Create an `NSNumber` instance from a Python `float` or `int`. Parameters: `py` - The value (`float` or `int`). Returns: The ObjC instance (`NSDouble`). Raises: `TypeError` - If `py` not a `float` or `int`.

### fontTraits(*traits) |
Return a font traits mask for the named traits. Parameters: `traits` - Trait names (`str`s), case-insensitive. Returns: Combined traits (`FontTrait` `s mask`). Raises: `FontTraitError` - One or more traits are invalid.

### fontTraitstrs(traits) |
Return font traits as names. Parameters: `traits` - Traits (`FontTrait` `s mask`). Returns: Tuple of trait names (`str`s).

### fontfamilies(*prefixes) |
Yield the installed font families. Parameters: `prefixes` - No, one or more font family names to match (`str`-s). Returns: Each font family name (`str`).

### fontnamesof(family) |
Yield the available font names of a family. Parameters: `family` - Generic font name (`str`), like "Times" or "Helvetica". Returns: The name (`str`) of each font.

### fontsof(family, size=0, weight=None) |
Yield the available fonts of a family. Parameters: `family` - Generic font name (`str`), like "Times" or "Helvetica". `size` - The point size (`int`), zero for any. `weight` - The book weight (`int`), None for any. Returns: A (Font) instance for each font. Raises: `ValueError` - Invalid weight.

### fontsof4(family) |
Yield the available fonts of a family. Parameters: `family` - Generic font name (`str`), like "Times" or "Helvetica". Returns: 4-Tuple (name, attributes, weight, traits) of (`str`, `str`, `int`, `int`) for each font.

### frozenset2NS(py) |
Create an (immutable) `NSSet` instance from a Python `frozenset`. Parameters: `py` - The value (`frozenset`). Returns: The ObjC instance (`NSSet`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### gcd(a, b) |
Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive).

### generator2NS(py) |
Create an `NSArray` instance from a Python `generator`. Parameters: `py` - The value (`generator`). Returns: The ObjC instance (`NSArray`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### getUncaughtExceptionHandler() |
Get the currently installed uncaught `ObjC/NSException` handler. Returns: The installed handler (`callable`) or `None` if no handler was or couldn't be installed (like on macOS 12.0.1 Monterey, for example).

### get_c_func_t(encoding, codes=None) |
Get the `ctypes` function type for a given function signature. Parameters: `encoding` - Type encoding of the signature (`str` or `bytes`). `codes` - The individual type codes (`type encoding`[]) Note: The signature encoding is a `str` or `bytes`, not unicode and codes is a list of the individual type encodings, limited to basic type encodings and pointers to basic type encodings. Does not handle `array`s, `bitfield`s, arbitrary `struct`s and `union`s. If keyword codes is not supplied, it will be created from the signature by split_encoding, not split_emcoding2.

### get_class(name) |
Get a registered ObjC class by name. Parameters: `name` - The class name (`str`). Returns: The class (Class_t) if found, None otherwise.

### get_classes(*prefixes) |
Yield all loaded ObjC classes with a name starting with one of the given prefixes. Parameters: `prefixes` - No, one or more class names to match (`str`-s). Returns: For each class yield a 2-tuple (name, class) where name is the class name and class is the ObjC Class_t object.

### get_classname(clas, dflt=missing) |
Get the name of an ObjC class. Parameters: `clas` - The class (Class_t). Returns: The class name (`str`). Raises: `ValueError` - Invalid clas, iff no dflt provided.

### get_classnameof(objc, dflt=missing) |
Get the name of the ObjC class of an object. Parameters: `objc` - The object (`Object` or Id_t). Returns: The object's class name (`str`). Raises: `ValueError` - Invalid objc, iff no dflt provided.

### get_classof(objc) |
Get the ObjC class of an object. Parameters: `objc` - The object (`Object` or Id_t). Returns: The object's class (Class_t) if found, None otherwise.

### get_inheritance(clas) |
Yield the inheritance of an ObjC class. Parameters: `clas` - Class (Class_t). Returns: The parent classes (Class_t), in bottom-up order.

### get_ivar(objc, name, ctype=None) |
Get the value of an instance variable (ivar). Parameters: `objc` - The object (`Object` or Id_t). `name` - The instance variable name (`str`). `ctype` - The instance variable type (`ctypes`), Returns: The ivar value (`any`) if found, None otherwise.

### get_ivars(clas, *prefixes) |
Yield all instance variables (ivar) of an ObjC class with a name starting with one of the given prefixes. Parameters: `clas` - The class (Class_t). `prefixes` - No, one or more ivar names to match (`str`-s). Returns: For each ivar yield a 4-tuple (name, encoding, ctype, ivar) where name is the ivar name, encoding is the ivar's type encoding, ctype is the ivar's `ctypes` type and ivar the Ivar_t object.

### get_lib(name) |
Find and load a `.dylib` library. Parameters: `name` - The library base name (`str`). Returns: The library (`ctypes.CDLL`). Note: Private attribute `._name` shows the library path.

### get_libPC() |
Get the `PrintCore` framework library. Returns: The `libPC` framework library (`ctypes.CDLL`).

### get_lib_framework(name, services=`'``ApplicationServices``'`, version='') |
Load a `Frameworks services .framework` library. Parameters: `name` - Library base name (`str`). `services` - Services framework base name (`str`). `version` - Framework version (`str`), if not 'Current'. Returns: The library (`ctypes.CDLL`). Note: Private attribute `._name` shows the library path. Example: get_lib_framework('PrintCore') get_lib_framework('Metadata', services='CoreServices')

### get_libs() |
Return the `.dylib` libraries loaded so far. Returns: The libraries cached (`Adict`).

### get_metaclass(name) |
Get a registered ObjC metaclass by name. Parameters: `name` - The metaclass (`str`). Returns: The metaclass (Class_t) if found, None otherwise.

### get_method(clas, name) |
Get a method of an ObjC class by name. Parameters: `clas` - Class (Class_t). `name` - Method name (`str`). Returns: The method (Method_t) if found, None otherwise.

### get_methods(clas, *prefixes) |
Yield all methods of an ObjC class with a name starting with one of the given prefixes. Parameters: `clas` - The class (Class_t). `prefixes` - No, one or more method names to match (`str`-s). Returns: For each method yield a 4-tuple (name, encoding, rargtypes, method), where name is the method name, encoding is the type encoding of the method signature including the return type, rargtypes the `ctypes` signature, the argtypes `list`** preceeded by the restype and method the Method_t object. Note: In Python 3+ rargtypes is a `map` object, not a `list`.

### get_papers(*printers) |
Yield the papers available at the given printer(s). Parameters: `printers` - No, one or more printers (Printers). Returns: Each paper (Paper).

### get_printer(*prefixes) |
Find a printer by name or by ID or get the default printer. Parameters: `prefixes` - No, one or more printer names or IDs to match (`str`s). Returns: The printer (Printer) or `None` if none found.

### get_printer_browser(server=None) |
Show the printer browser for the given server. Parameters: `server` - Print server (`PMServer`) or `None` for this server, the localhost. Returns: Printers (`dict`) or `None`.

### get_printers(server=None) |
Yield all printers available at the given server. Parameters: `server` - Print server (`PMServer`) or `None` for this server, the localhost. Returns: Each printer (Printer).

### get_properties(clas_or_proto, *prefixes) |
Yield all properties of an ObjC class or protocol with a name starting with one of the given prefixes. Parameters: `clas_or_proto` - The class or protocol (Class_t or Protocol_t). `prefixes` - No, one or more property names to match (`str`-s). Returns: For each property, yield a 3-tuple (name, attributes, setter, property) where attributes is a comma-separated list of the property attibutes, setter is the name of the property setter method, provided the property is writable and property is the `Property` object. For read-only properties, the setter is an empty name "". Note: ObjC Property Attributes: T<type>"name" = Type & = Retain last value (retain) C = Copy D = Dynamic (@dynamic) G<name> = Getter selector name N = Non-atomic (nonatomic) P = To be garbage collected R = Read-only (readonly) S<name> = Setter selector name t<encoding> = Old-style type encoding W = Weak reference (__weak) See Also: Property Attributes.

### get_protocol(name) |
Get a registered ObjC protocol by name. Parameters: `name` - The protocol name (`str`). Returns: The protocol (Protocol_t) if found, None otherwise.

### get_protocols(clas, *prefixes) |
Yield all protocols of an ObjC class with a name starting with one of the given prefixes. Parameters: `clas` - The class (Class_t). `prefixes` - No, one or more protocol names to match (`str`-s). Returns: For each protocol, yield a 2-tuple (name, protocol) where name is the protocol name and protocol the Protocol_t object.

### get_resolutions(*printers) |
Yield the resolutions supported by the given printer(s). Parameters: `printers` - No, one or more printers (Printers). Returns: Each resolution 2-tuple (horizontal, vertical) in dots per inch (`float`s).

### get_selector(name_) |
Get an ObjC selector by name. Parameters: `name_` - The selector name (`str`). Returns: The selector (SEL_t) if found, `None` otherwise.

### get_selectorname_permutations(name_, leading=False) |
Yield all permutations of a Python-style selector name. Parameters: `name_` - The selector name with underscores (`str`). `leading` - In-/exclude leading underscores in name_ permutations (`bool`), default `False` meaning exclude. Returns: The selector name (`str`) for each underscore and colon permutation. Note: Only the underscores in name_ are permuted, any colons in name_ remain unchanged.

### get_selectornameof(sel) |
Get the name of an ObjC selector. Parameters: `sel` - The selector (SEL_t). Returns: The selector name (`str`) if found, `""` otherwise.

### get_superclass(clas) |
Get the ObjC super-class of an ObjC class. Parameters: `clas` - The class (Class_t). Returns: The super-class (Class_t), None otherwise.

### get_superclassnameof(objc, dflt=missing) |
Get the name of the ObjC super-class of an object. Parameters: `objc` - The object (`Object` or Id_t). Returns: The object'ssuper-class name (`str`). Raises: `ValueError` - Invalid objc, iff no dflt provided.

### get_superclassof(objc) |
Get the ObjC super-class of an object. Parameters: `objc` - The object (`Object` or Id_t). Returns: The super-class (Class_t), None otherwise.

### inst2strepr(inst, strepr, *attrs) |
Convert an instance's attributes, maintaining the order. Parameters: `inst` - Instance (`any`). `strepr` - Conversion (`repr` or `str`). `attrs` - Instance attribute names (all positional). Returns: Instance representation (`str`).

### int2NS(py) |
Create an `NSNumber` instance from a Python `int` or `long`. Parameters: `py` - The value (`int` or `long`). Returns: The ObjC instance (`NSInt`, `NSLong`, or `NSLongLong`). Raises: `TypeError` - If `py` not an `int` or `long`.

### isAlias(path) |
Resolve a macOS file or folder alias. Parameters: `path` - The alias name (`str` or NSStr). Returns: The alias' target (`str`) or `None` if path isn't a macOS alias. See Also: mac-alias and here.

### isClass(objc) |
Check whether an object is an ObjC clas. Parameters: `objc` - Object to check (`Object` or `Class`). Returns: True if the objc is a clas, False otherwise.

### isImmutable(objc, mutableClass, immutableClass, name=`'``ns``'`) |
Check that an ObjC object is an instance of the immutable class. Parameters: `objc` - The instance to check (ObjCInstance). `mutableClass` - The mutable ObjC classes (`NSMutable...`). `immutableClass` - The immutable ObjC classes (`Object`). `name` - The name of the instance (`str`). Returns: True if objc is an immutableClass instance, False otherwise. Raises: `TypeError` - If objc is a mutableClass instance, provided keyword argument name='...' is given.

### isLink(path) |
Resolve a file or folder link or alias. Parameters: `path` - The link or alias name (`str` or NSStr). Returns: The link's or alias' target (`str`) or `None` if path isn't a link or alias.

### isMetaClass(objc) |
Check whether an object is an ObjC metaclass. Parameters: `objc` - Object to check (`Object` or `Class`). Returns: True if the objc is a metaclass, False otherwise.

### isNone(obj) |
Return True if obj is `None, NSMain.nil, NSMain.Null`, etc. Parameters: `obj` - The object (ObjCInstance). Returns: True or False (`bool`).

### isObjCInstanceOf(objc, *Classes, **name_missing) |
Check whether an ObjC object is an instance of some ObjC class. Parameters: `objc` - The instance to check (ObjCInstance or `c_void_p`). `Classes` - One or several ObjC classes (`Object`). `name` - The name of the instance (`str`). Returns: The matching Class from Classes, None otherwise. Raises: `TypeError` - If objc is not an ObjCInstance or `c_void_p` or if objc does not match any of the Classes and only if keyword name='...' is provided. See Also: Function isinstanceOf for checking Python instances.

### is_enabled(sig=None) |
Check whether `fault` handling is enabled, similar to the faulthandler module available in Python 3.3 and later. Parameters: `sig` - Check whether `fault` handling includes this signal (`signal.SIG*`). Returns: `True` if `fault` handling is currently enabled, `False` otherwise.

### isinstanceOf(inst, *classes, **name_missing) |
Check a Python instance' class. Parameters: `inst` - The instance to check (any). `classes` - One or several classes (all positional). `name` - The name of the instance (`str`). Returns: The matching class from classes, None otherwise. Raises: `TypeError` - If inst does not match any of the classes, but iff keyword name='...' is provided. See Also: Function isObjCInstanceOf for checking ObjC instances.

### iterbytes(collection) |
iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. Returns: iterator

### leaked2() |
Return the number of memory leaks. Returns: 2-Tuple (number, size) with the number of memory leaks and total size leaked, in bytes.

### list2NS(py) |
Create an `NSMutableArray` instance from a Python `list`. Parameters: `py` - The value (`list`). Returns: The ObjC instance (`NSMutableArray`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### logf(fmt, *args, **kwds) |
Formatted log fmt % args with optional keywords. Parameters: `fmt` - Print-like format or plain string (`str`). `args` - Optional arguments to format (all positional). `argv0` - Optional prefix (`str`). `file` - Alternate file to write to (`file`-type), default `NSMain.stdlog`. `flush` - Flush `file` after writing (`bool`), default C(True). `nl` - Number of leading blank lines (`int`). `nt` - Number of trailing blank lines (`int`).

### machine() |
Return the `platform.machine` string, distinguishing Intel from emulating Intel on Apple Silicon (on macOS). Returns: Machine `'arm64'` for Apple Silicon, `"arm64_x86_64"` for Intel emulated, `'x86_64'` for Intel, etc. (`str` with any `comma`s by `underscore`).

### map2NS(py) |
Create an `NSArray` instance from a Python `map`. Parameters: `py` - The value (`map`). Returns: The ObjC instance (`NSArray`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### name2objc(name_) |
Convert a (selector) name to `bytes` and ObjC naming rules. Parameters: `name_` - Name to convert (`str` or `bytes`). Returns: Converted name (`bytes`). Note: A name_ starting with an underscore is returned as-is.

### name2py(name_) |
Convert a (selector) name `str` and Python naming conventions. Parameters: `name_` - Name to convert (`str` or `bytes`). Returns: Converted name (`str`). Note: A name_ starting with an underscore is returned as-is.

### name2pymethod(name_) |
Convert a (selector) name to a valid Python callback method. Parameters: `name_` - Name to convert (`str` or `bytes`). Returns: Converted name (`str`). Raises: `ValueError` - Invalid, non-alphanumeric name_.

### ns2App(ns) |
Get the App instance from an `NSApplication` or an `NSNotification` instance. Parameters: `ns` - The ObjC instance (`NS...`). Returns: The app instance (App). Raises: `RuntimeError` - App mismatch. `TypeError` - Invalid ns type.

### ns2Item(ns) |
Get the Python instance for an `NSMenuItem`. Parameters: `ns` - The ObjC instance (`NSMenuItem`). Returns: The instance (Item or Menu). Raises: `TypeError` - Invalid ns type. Note: A Menu instance is returned if ns was an intermediate `NSMenuItem`, created internally to append or insert a Menu to a MenuBar.

### ns2Type(ns) |
Convert an `NS...` ObjC object to an instance of the corresponding Python Type and value. Parameters: `ns` - The `NS...` (ObjCInstance). Returns: The value (`Python Type`).

### ns2TypeID2(ns, dflt=None) |
Get the `NS...` ObjC `TypeID`. Parameters: `ns` - The `NS...` (ObjCInstance). `dflt` - Default for unhandled, unexpected `NS...`s (`missing`). Returns: 2-Tuple `(TypeID, ns...2py)` of an `int`NS and the type conversion `callable`.

### ns2Window(ns) |
Get the Window instance for an ObjC `NSWindow` or `NSNotification` instance. Parameters: `ns` - The ObjC instance (`NS...`). Returns: The window instance (Window). Raises: `AttributeError` - Unexpected ns type. `RuntimeError` - Window mismatch. `TypeError` - Invalid ns type.

### ns2py(ns, dflt=missing) |
Convert (an instance of) an ObjC class to an instance of the equivalent Python standard type or wrapper and value. Parameters: `ns` - The `NS...` (ObjCInstance). `dflt` - Default for unhandled, unexpected `NS...`s (`missing`). Returns: The value (`Python type`) or dflt if provided. Raises: `TypeError` - Unhandled, unexpected `TypeID`. Note: Conversion map: NSArray -> tuple NSBoolean -> bool NSConstantString -> str NSData -> bytes NSDecimalNumber -> Decimal NSDictionary -> dict NSMutableArray -> list NSMutableSet -> set NSMutableString -> str NSNumber -> int or float NSNull -> None NSSet -> frozenset NSString -> str NSStr -> str See Also: Converting values between Python and Objective-C

### nsArray2listuple(ns, ctype=<class 'ctypes.c_void_p'>) |
Create a Python `list` or `tuple` from an `NS[Mutable]Array`. Parameters: `ns` - The `NS[Mutable]Array` (ObjCInstance). `ctype` - The array item type (`ctypes`). Returns: The array (`list` or `tuple`).

### nsArray2tuple(ns, ctype=<class 'pycocoa.runtime.ObjCInstance'>) |
Create a Python `tuple` from an immutable `NSArray`. Parameters: `ns` - The `NSArray` (ObjCInstance). `ctype` - The array item type (`ObjCInstance`). Returns: The array (`tuple`).

### nsBoolean2bool(ns, dflt=missing) |
Create a Python `bool` from an `NSBoolean`. Parameters: `ns` - The `NSBoolean` (ObjCInstance). `dflt` - Default for a missing, unobtainable value (`missing`). Returns: The bool (`bool`) of dlft. Raises: `TypeError` - Unexpected `NumberType`.

### nsBundleRename(ns_title, match=`'``Python``'`) |
Change the bundle title if the current title matches. Parameters: `ns_title` - New bundle title (NSStr). `match` - Optional, previous title to match (`str`). Returns: The previous bundle title (`str`) or None. Note: Used to mimick `NSApplication.setTitle_(ns_title)`, the name of an App shown in the menu bar.

### nsData2bytes(ns, dflt=`'````'`) |
Create Python `bytes` from `NSData`. Parameters: `ns` - The `NSData` (ObjCInstance). `dflt` - Default for empty `NSData` (`bytes`). Returns: The bytes (`bytes`) or dflt.

### nsDecimal2decimal(ns) |
Create a Python `Decimal` from an `NSDecimalNumber`. Parameters: `ns` - The `NSDecimalNumber` (ObjCInstance). Returns: The decimal (`Decimal`). Raises: `ValueError` - If ns not an `NSNumber`.

### nsDictionary2dict(ns, ctype_keys=<class 'ctypes.c_void_p'>, ctype_vals=<class 'ctypes.c_void_p'>) |
Create a Python `dict` from an `NS[Mutable]Dictionary`. Parameters: `ns` - The `NSDictionary` instance (ObjCInstance). `ctype_keys` - The dictionary keys type (`ctypes`). `ctype_vals` - The dictionary values type (`ctypes`). Returns: The dict (Adict).

### nsDictionary2items(ns) |
Yield the `(key, value)` items from an `NSDictionary`. Parameters: `ns` - The `NSDictionary` instance (ObjCInstance). Returns: A 2-tuple `(key, value)` for each item, each a separate ObjCInstance

### nsException(name=None, reason=`'``not given``'`, **info) |
Create an `ObjC/NSException` instance. Parameters: `name` - Ignored (NSExceptionName). `reason` - The reason for the exception (`str`). `info` - Other, caller-defined information (`all keywords`). See Also: nsRaise, nsThrow and NSExceptionError. Notes: Use NSExceptionError`(nsExc)` to wrap a Python exception around an `ObjC/NSException` instance and get access to the attributes of the latter. Raised and thrown `NSException`s can not be caught and result in fatal exiting.

### nsIter(ns, reverse=False) |
Iterate over an `NS..` ObjC objects's (reverse) enumerator. Parameters: `ns` - The `NS..` object to iterate over (ObjCInstance). `reverse` - Iterate in reverse order (`bool`), forward otherwise. Returns: Each object (`NS...`).

### nsIter2(ns, reverse=False) |
Iterate over an `NS..` ObjC objects's (reverse) enumerator. Parameters: `ns` - The `NS..` object to iterate over (ObjCInstance). `reverse` - Iterate in reverse order (`bool`), foward otherwise. Returns: Each object as 2-Tuple (py, ns) where py is a Python `Type` instance and ns the ObjC object `NS...`.

### nsLog(ns_fmt, *ns_args) |
Formatted ObjC write to the console. Parameters: `ns_fmt` - A printf-like format string (NSStr). `ns_args` - Optional arguments to format (`all positional`). Note: The ns_fmt and all ns_args must be `NS...` ObjC instances. See Also: Dglessus' nslog.py.

### nsLogf(fmt, *args) |
Formatted write to the console. Parameters: `fmt` - A printf-like format string (`str`). `args` - Optional arguments to format (`all positional`). See Also: nsLog.

### nsNull2none(ns) |
Return Python `None` for an `NS/CFNull` or `nil`. Parameters: `ns` - The `NS...` (ObjCInstance). Returns: The singleton (`None`). Raises: `ValueError` - If ns not `isNone`.

### nsNumber2num(ns, dflt=missing) |
Create a Python `Decimal`, `int` or `float` from an `NSNumber`. Parameters: `ns` - The `NSNumber` (ObjCInstance). `dflt` - Default for missing, unobtainable value (`missing`). Returns: The number (`Decimal`, `int` or `float`). Raises: `TypeError` - Unexpected `NumberType`. `ValueError` - If ns not an `NSNumber`.

### nsOf(inst) |
Return the `.NS` ObjC object of a Python wrapper or Type instance. Parameters: `inst` - The wrapper (ObjCInstance or `Python Type`). Returns: The `.NS` object (`NS...`). Raises: `TypeError` - No `.NS` for this inst.

### nsRaise(name=None, reason=`'``not given``'`, **info) |
Create an `NSException` and mimick `@throw NSException`. Parameters: `name` - Ignored (NSExceptionName). `reason` - The reason for the exception (`str`). `info` - Other, caller-defined information (`all keywords`). Note: Raised `NSException`s can not be caught and result in fatal exiting. See Also: NSException and nsThrow.

### nsSet2set(ns, ctype=<class 'ctypes.c_void_p'>) |
Create a Python `set` or `frozenset` from an `NS[Mutable]Set`. Parameters: `ns` - The `NS[Mutable]Set` (ObjCInstance). `ctype` - The set item type (`ctypes`). Returns: The set (`set` or `frozenset`).

### nsString2str(ns, dflt=None) |
Create a Python `str` or `unicode` from an `NS[Mutable]Str[ing]`. Parameters: `ns` - The `NS[Mutable]Str[ing]` (ObjCInstance). Returns: The string (`str` or `unicode`) or dflt.

### nsTextSize3(text, ns_font=None) |
Return the size of a multi-line text. Parameters: `text` - The text (`str`), including `linesep`arators. `ns_font` - The text font (`NSFont`) or `None`. Returns: 3-Tuple (width, height, lines) in (pixels, pixels) or in (characters, lines, lines) if ns_font is `None`.

### nsThrow(nsExc) |
Mimick ObjC's `@throw NSException` to raise an exception. Parameters: `nsExc` - The exception to raise (`NSException`). Raises: `TypeError` - Invalid `nsExc`. See Also: NSException and nsRaise. Note: Thrown `NSException`s can not be caught and result in fatal exiting.

### nsURL2str(ns) |
Create a Python `str` from `NSURL` string. Parameters: `ns` - The `CFURL` (ObjCInstance). Returns: The URL as string (`str`).

### nsValue2py(ns, dflt=missing) |
Create a Python instance from an `NS[Concrete]Value`. Parameters: `ns` - The `NS[Concrete]Value` (ObjCInstance). `dflt` - Default for missing, unobtainable value. Returns: The value (`NSPoint_t`, `NSRange_t`, `NSRect_t`, `NSSize_t` or `tuple`) or `dflt`. Raises: `TypeError` - Invalid `ns` or unexpected `ns.objCType`.

### printf(fmt, *args, **kwds) |
Formatted print fmt % args with optional keywords. Parameters: `fmt` - Print-like format or plain string (`str`). `args` - Optional arguments to format (all positional). `argv0` - Optional prefix (`str`). `file` - Alternate file to write to (`file`-type), default `sys.stdout`. `flush` - Flush `file` after writing (`bool`), default `False`. `nl` - Number of leading blank lines (`int`). `nt` - Number of trailing blank lines (`int`).

### properties(inst) |
All property names and values. Parameters: `inst` - An instance (`any`). Returns: The properties (`dict`).

### property2(inst, name) |
Return the property `get` and `set` method. Parameters: `inst` - An instance (`any`). `name` - Property name (`str`). Returns: 2-Tuple (get, set) as `callable`s, (`callable`, `None`) or (`None`, `None`) if inst.name is not a property.

### property_RO(method) |
Decorator for `Read_Only` class/instance property. Parameters: `method` - The callable to be decorated as `property`. Note: Like standard Python `property` without a `property.setter` with a more descriptive error message when set.

### py2NS(py) |
Convert (an instance of) a Python object into an instance of the equivalent `NS...` ObjC class: Parameters: `py` - The value (`Python type`). Returns: The ObjC instance (ObjCInstance). Raises: `TypeError` - Unhandled, unexpected `Python type`. Note: Conversion map: bool -> NSBoolean/NSNumber bytes -> NSData (Python 3+ only) bytearray -> NSData Decimal -> NSDecimal dict -> NSMutableDictionary float -> NSNumber frozenset -> NSSet, immutable generator -> NSArray, immutable (like tuple) int -> NSNumber list -> NSMutableArray map -> NSArray, immutable (like tuple, Python 3+ only) None -> NSNull range -> NSArray, immutable (like tuple) set -> NSMutableSet str -> NSStr, immutable tuple -> NSArray, immutable unicode -> NSStr, immutable See Also: Converting values between Python and Objective-C

### range2NS(py) |
Create an `NSArray` instance from a Python `range`. Parameters: `py` - The value (`range`). Returns: The ObjC instance (`NSArray`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### register_subclass(subclas) |
Register an ObjC sub-class. Parameters: `subclas` - Class to be registered (`Class`). See Also: ObjCSubclass`.register`.

### release(objc) |
Release an ObjC instance to be deleted, eventually. Parameters: `objc` - The instance to release (ObjCInstance). Returns: The instance objc. Raises: `TypeError` - If objc is not releasable. Note: May result in Python memory errors, aborts and/or segfaults. Use 'python3 -X faulthandler ...' to get a Python traceback in such circumstances.

### retain(objc) |
Preserve an ObjC instance from destruction. Parameters: `objc` - The instance to retain (ObjCInstance). Returns: The retained instance objc. Raises: `TypeError` - If objc is not retainable. Note: May result in Python memory errors, aborts and/or segfaults. Use 'python3 -X faulthandler ...' to get a Python traceback in such circumstances.

### send_message(objc, sel_name_, *args, **resargtypes) |
Send message to an ObjC object. Parameters: `objc` - The recipient (`Object`, `Id_t`, etc.) instance. `sel_name_` - Message selector (`SEL_t`) or name (`str` or `bytes`). `args` - Message arguments (all positional). `resargtypes` - Optional, result and argument types (`ctypes`). Returns: Message result (restype). Raises: `ArgumentError` - Invalid objc, sel_name_, args or resargtypes. `TypeError` - Invalid objc, sel_name_, args or resargtypes type. Note: By default, the result and any arguments are `c_void_p` wrapped. Use keyword arguments restype=c_void_p and argtypes=[] to change the defaults. The restype defines the `ctypes` type for the returned result and argtypes is the list of `ctypes` types for the message arguments only without the `Id/self` and `SEL/cmd` arguments.

### send_super(objc, sel_name_, *args, **resargtypes) |
Send message to the super-class of an ObjC object. Parameters: `objc` - The recipient (`Object`, `Id_t`, etc.) instance. `sel_name_` - Message selector (`SEL_t`) or name (`str` or `bytes`). `args` - Message arguments (all positional). `resargtypes` - Optional, result and argument types (`ctypes`). Returns: Message result (restype). Raises: `ArgumentError` - Invalid objc, sel_name_, args or resargtypes. `TypeError` - Invalid objc, sel_name_, args or resargtypes type. Note: By default, the result and any arguments are `c_void_p` wrapped. Use keyword arguments restype=c_void_p and argtypes=[] to change the defaults. The restype defines the `ctypes` type for the returned result and argtypes is the list of `ctypes` types for the message arguments only without the `Id/self` and `SEL/cmd` arguments.

### send_super_init(objc) |
Send 'init' message to the super-class of an ObjC object. Parameters: `objc` - The recipient (`Object`, `Id_t`, etc.) instance. Returns: Message result (`Id_t`).

### set2NS(py) |
Create an `NSMutableSet` instance from a Python `set`. Parameters: `py` - The value (`set`). Returns: The ObjC instance (`NSMutableSet`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### setUncaughtExceptionHandler(handler, log=True, raiser=False) |
Install a callback to handle uncaught `ObjC/NSException`s. The `handler(error)` is called with one argument `error`, an NSExceptionError instance. It should return that same `error`, an exiting `status` or `None`. In in former case, that `error` will subsequently be raised as Python exception. Parameters: `handler` - A callable to be invoked with a single argument `error`, an NSExceptionError instance and to return that same `error`, an exiting `status` or `None`. `log` - Print the `error`, an time stamp and -if avilable- the ObjC callstack and Python traceback prior to invoking the `handler` (`bool`). `raiser` - Raise the NSExceptionError `error`, regardless of the return value from the `handler`. Returns: The previously installed uncaught `ObjC/NSException` handler or `None` if no handler was or couldn't be installed. Raises: `RuntimeError` - Setting uncaught exception handlers unavailable, but only thrown if `raiser`=True. `TypeError` - The `handler` is not callable. Notes: Faults like `SIGILL`, `SIGSEGV`, etc. do not throw uncaught `ObjC/NSException`s and will not invoke the given `handler`. However, those and several other signals can be handled as `fault`s, see faults.enable, faults.disable and other functions module faults. An uncaught `ObjC/NSException` always results in (graceful) termination of the process. Uncaught `ObjC/NSException`s are not reported to an `NSLog` file (yet). See Also: Dgelessus' pythonista_startup.py, Handling Exceptions and Error Handling Programming Guide.

### set_ivar(objc, name, value, ctype=None) |
Set an instance variable of an ObjC object. Parameters: `objc` - The instance (`Object`). `name` - Name of the ivar (`str`). `value` - New value for the ivar (`any`). `ctype` - Optional, the ivar type (`ctypes`). Returns: The ivar (Ivar_t). Raises: `ArgumentError` - Invalid name, value or ctype. `TypeError` - Invalid name, value or ctype type.

### split_emcoding2(encoding, start=0) |
Split the type encoding of a method signature into separate, single encodings and the combined encoding. If necessary, the encoding is extended with the type encoding for the hidden method arguments `Id/self` and `SEL/cmd`. Returns: 2-Tuple (codes, encoding), where codes is the list of individual type encodings from item start=0 and encoding is the combined type encoding in `bytes`, both extended with `Id/self` and `SEL/cmd` iff needed. Raises: `TypeCodeError` - Invalid or unbalanced encoding. Note: Does not handle `bitfield`s, `array`s, `struct`s, `union`s, etc. and strips any offset, size or width specifiers from the encoding. Example:
    >>> split_emcoding2('v*')
    >>> (['v', '@', ':', '*'], 'v@:*')

### split_encoding(encoding) |
Split a type encoding into separate type encodings. Does not handle `bitfield`s, `array`s, `struct`s, `union`s, etc. and strips any offset, size or width specifiers from the encoding. Returns: The individual type encodings (`list`). Raises: `TypeCodeError` - Invalid or unbalanced encoding. Example:
    >>> split_encoding('^v16@0:8')
    >>> ['^v', '@', ':']
    >>> split_encoding('{CGSize=dd}40@0:8{PyObject=@}Q32')
    >>> ['{CGSize=dd}', '@', ':', '{PyObject=@}', 'Q']
Supported Type Encodings: B = bool (C++ bool, C99 _Bool) c, C = char, unsigned char f, d = float, double i, I = int, unsigned int l, L = long, unsigned long (32-bit in 64-bit Apps) q, Q = long long, unsigned long long s, S = short, unsigned short t, T = 128-bit int, unsigned int v = void * = string (char *) : = method selector `SEL/cmd` # = class #"name" = class "name" @ = object instance `Id/self` or statically typed @"name" = instance `Id/self` of class "name" ^type = pointer to type ? = unknown type (among other things, used for function pointers) PyCocoa specific: P = Python object, shorthand for `PyObjectEncoding` Unsupported Type Encodings: bW = bitfield of width W [Ltype] = array of L items of type {name=type...} = structure (name=type...) = union <...> = block ?<...> = block with signature Unknown or for ObjC internal use: A = ? j = ? n, N = in, inout o, O = out, bycopy r, R = const, byref V = oneway Note: Type encodings may be preceeded by `"name"`, for example a `bitfield` `"name"b1`, `struct` items `{CGsize="width"d"heigth"d}`, `union` items, etc. and all such `"name"` prefixes are ignored. See Also: Type Encodings, NSHipster Type Encodings and Digits in type encoding.

### str2NS(py) |
Create an `NSStr` instance from a Python `str`. Parameters: `py` - The value (`str`). Returns: The ObjC instance (`NSStr`).

### str2bytes(bytestr, dflt=missing, name='') |
Convert `str` to `bytes`/`unicode` if needed. Parameters: `bytestr` - `bytes`, `str` or `unicode`. `dflt` - Optional, default return value. `name` - Optional name of bytestr argument. Returns: `bytes` or dflt. Raises: `TypeError` - If neither `bytes` nor `str`, but only if no dflt is provided.

### terminating(app, timeout=None) |
Set up a separate thread to terminate an NSApplication by calling the `.terminate_` method after the given timeout has elapsed. Returns: Timeout in seconds (`float`) or `None`. Note: Similarly, the NSWindow could be closed, provided the NSWindow or NSApplication `Delegate` instance includes the `.windowWillClose_` method which in turn terminates the NSApplication's `.terminate_` method.

### time2NS(py=None, since=1970) |
Create an `NSDate` instance from a timestamp. Parameters: `py` - The timestamp in seconds (`float`, `int`). `since` - Epoch start (1970, 2001) otherwise now. Returns: The ObjC instance (`NSDate`). Note: Using `py=None` means `py=0, since=None` or `py=time.time(), since=1970`.

### title2action(title) |
Convert a menu item `title` to a Python callback method name. Parameters: `title` - The item's title (`str`). Returns: Name for the Python callback method (`str`), the title with all non-alphanumeric characters except colon and underscore removed, with prefixed `"menu"` and suffix `"_"` added. Raises: `ValueError` - If title can not be converted.

### tuple2NS(py) |
Create an immutable `NSArray` instance from a Python `tuple`. Parameters: `py` - The value (`tuple`). Returns: The ObjC instance (`NSArray`). Raises: `RuntimeError` - If `len` vs `count` assertion failed.

### type2NS(py) |
Create the `NS...` ObjC object for a Python Type or wrapper instance. Parameters: `py` - The value (`Type`). Returns: The ObjC instance (ObjCInstance). Raises: `TypeError` - Unhandled, unexpected `Type`. See Also: Function py2NS.

### type2strepr(inst, strepr=<type 'str'>, **kwds) |
Represent a Python Type instance as `str` or `repr`. Parameters: `inst` - Instance (`any`). `strepr` - Representation function (`repr` or `str`). Returns: Instance representation (`str`).

### unicode2NS(py) |
Create an `NSStr` instance from a Python `unicode` string. Parameters: `py` - The value (`unicode`). Returns: The ObjC instance (`NSStr`).

### url2NS(py, url2=None) |
Create an `NSURL` instance from a Python string. Parameters: `py` - The URL (`str` or `unicode`). `url2` - Optionally, relative to this URL (`str` or `unicode`). Returns: The ObjC instance (`NSURL`). See Also: URL for parsing an `NSURL`.

### windowStyles(*styles) |
Return a combination of window styles, specified by name. Parameters: `styles` - Style names (all positional), case-insensitive. Returns: Combined styles (WindowStyles `mask`). Raises: `WindowStyleError` - One or more styles are invalid.

### z1000str(size, sep='_') |
Convert a size to string with 1_000's seperator. Parameters: `size` - Value to convert (`float` or `int`). `sep` - 1_000's separator (`str`). Returns: "<1or2digits><sep><3digits>..." or "-" if size is negative (`str`).

### zSIstr(size, B=`'``B``'`, K=1024) |
Convert a size to string with SI-units suffix. Parameters: `size` - Value to convert (`float` or `int`). `B` - The unit (`str`). `K` - 1024 or 1000 (`int`). Returns: "<Size> <SI>[i]<B>" (`str`).

### zfstr(flt, prec=3) |
Format a `float` and strip trailing zero decimals. Parameters: `flt` - Value (`float`). `prec` - Number of decimals (`int`). Returns: Value (`str`).

Variables Details

  ### pycocoa_abspath Value:
      '..../PyCocoa/
      pycocoa'

  ### AlertStyle Value:
      AlertStyle.Critical=2,
                .Info=1,
                .Warning=0

  ### AutoResize Value:
      AutoResize.HeightSizable=1<<4,
                .MaxXMargin=1<<2,
                .MaxYMargin=1<<5,
                .MinXMargin=1,
                .MinYMargin=1<<3,
                .NotSizable=0,
                .Sizable=18,
                .WidthSizable=2

  ### BezelStyle Value:
      BezelStyle.Disclosure=5,
                .HelpButton=9,
                .Inline=15,
                .NCircular=7,
                .Recessed=13,
                .RegularSquare=2,
                .Rounded=1,
                .RoundedDisclosure=14,
      ...

  ### Border Value:
      Border.Bezel=2,
            .Groove=3,
            .Line=1,
            .No=0

  ### CMYColors Value:
      CMYColors.Cyan=CMYColor(_NSTaggedPointerColor, name='Cyan'),
               .Magenta=CMYColor(_NSTaggedPointerColor, name='Magenta'),
               .Yellow=CMYColor(_NSTaggedPointerColor, name='Yellow')

  ### Colors Value:
      Colors.CMY=CMYColors,
            .GS=GrayScaleColors,
            .HSB=HSBColors,
            .RGB=RGBColors,
            .Tint=TintColors,
            .UI=UIColors

  ### FontTrait Value:
      FontTrait.Bold=2,
               .Compressed=1<<9,
               .Condensed=1<<6,
               .Expanded=1<<5,
               .Italic=1,
               .MonoSpace=1<<10,
               .Narrow=1<<4,
               .Poster=1<<8,
      ...

  ### Fonts Value:
      Fonts.App=Font({family='Helvetica', name='Helvetica', size=12, weight=
      5}),
           .Bold=Font({family='.AppleSystemUIFont', name='.AppleSystemUIFont
      Bold', size=13, traits='Bold', weight=9}),
           .BoldItalic=Font({family='.AppleSystemUIFont', name='.AppleSystem
      UIFontEmphasizedItalic', size=13, traits='Bold Italic', weight=9}),
           .Italic=Font({family='.AppleSystemUIFont', name='.AppleSystemUIFo
      ntItalic', size=13, traits='Italic', weight=5}),
      ...

  ### GrayScaleColors Value:
      GrayScaleColors.Black=GrayScaleColor(_NSTaggedPointerColor, name='Blac
      k'),
                     .Clear=GrayScaleColor(_NSTaggedPointerColor, name='Clea
      r'),
                     .DarkGray=GrayScaleColor(_NSTaggedPointerColor, name='D
      arkGray'),
                     .Gray=GrayScaleColor(_NSTaggedPointerColor, name='Gray'
      ),
      ...

  ### Keys Value:
      Keys.ACK=0x6,
          .Acknowledge=0x6,
          .BackSpace=0x8,
          .BackTab=0x19,
          .BEL=0x7,
          .Bell=0x7,
          .BS=0x8,
          .BT=0x19,
      ...

  ### Libs Value:
      Libs.AppKit=<CDLL 'AppKit.framework/AppKit', handle 7fff95603cc8 at 7f
      d6086924d0>,
          .C=<CDLL 'libc.dylib', handle 7fff956ec788 at 7fd6086809d0>,
          .CoreFoundation=<CDLL 'CoreFoundation.framework/CoreFoundation', h
      andle 7fff956063c0 at 7fd608680f10>,
          .CoreGraphics=<CDLL 'CoreGraphics.framework/CoreGraphics', handle
      7fff956fc058 at 7fd608692a10>,
          .CoreText=<CDLL 'CoreText.framework/CoreText', handle 7fff956002f8
      ...

  ### NSApplicationDelegate Value:
      <pycocoa.utils.module_property_RO object at 0x7fd608434a50>

  ### NSDefaultRunLoopMode Value:
      RunLoop_t.in_dll(libAppKit, 'NSDefaultRunLoopMode')

  ### NSEventTrackingRunLoopMode Value:
      RunLoop_t.in_dll(libAppKit, 'NSEventTrackingRunLoopMode')

  ### NSMain Value:
      NSMain.Application=NSApplication(<Id_t at 0x7fd608a860e0>) of 0x7fd612
      0caec0,
            .BooleanNO=NSBoolean(<Id_t at 0x7fd608a69440>) of 0x7ff8526f2c70
      ,
            .BooleanYES=NSBoolean(<Id_t at 0x7fd608a96d40>) of 0x7ff8526f2c6
      0,
            .Bundle=NSBundle(<Id_t at 0x7fd608a96950>) of 0x600003de4000,
            .BundleName=NSConstantString('CFBundleName'),
      ...

  ### NSTableViewDelegate Value:
      <pycocoa.utils.module_property_RO object at 0x7fd608620190>

  ### NSWindowDelegate Value:
      <pycocoa.utils.module_property_RO object at 0x7fd6183fbed0>

  ### PanelButton Value:
      PanelButton.Cancel=0,
                 .Close=1,
                 .Error=-3,
                 .OK=1,
                 .Other=2,
                 .Suppressed=-2,
                 .TimedOut=-1

  ### RGBColors Value:
      RGBColors.Blue=RGBColor(_NSTaggedPointerColor, name='Blue'),
               .Brown=RGBColor(_NSTaggedPointerColor, name='Brown'),
               .Green=RGBColor(_NSTaggedPointerColor, name='Green'),
               .Orange=RGBColor(NSCachedRGBColor, name='Orange'),
               .Purple=RGBColor(NSCachedRGBColor, name='Purple'),
               .Red=RGBColor(_NSTaggedPointerColor, name='Red')

  ### Screens Value:
      (BuiltInScreen(NSScreen, name='BuiltIn'), ExternalScreen(NSScreen, nam
      e='External'))

  ### TintColors Value:
      TintColors.Blue=TintColor(NSDynamicSystemColor, name='Blue'),
                .Brown=TintColor(NSDynamicSystemColor, name='Brown'),
                .Gray=TintColor(NSDynamicSystemColor, name='Gray'),
                .Green=TintColor(NSDynamicSystemColor, name='Green'),
                .Indigo=TintColor(NSDynamicSystemColor, name='Indigo'),
                .Orange=TintColor(NSDynamicSystemColor, name='Orange'),
                .Pink=TintColor(NSDynamicSystemColor, name='Pink'),
                .Purple=TintColor(NSDynamicSystemColor, name='Purple'),
      ...

  ### UIColors Value:
      UIColors.Control=UIColor(NSDynamicSystemColor, name='Control'),
              .ControlBackground=UIColor(NSDynamicSystemColor, name='Control
      Background'),
              .Grid=UIColor(NSDynamicSystemColor, name='Grid'),
              .HeaderText=UIColor(NSDynamicSystemColor, name='HeaderText'),
              .Highlight=UIColor(NSDynamicSystemColor, name='Highlight'),
              .Label=UIColor(NSDynamicSystemColor, name='Label'),
              .Link=UIColor(NSDynamicSystemColor, name='Link'),
      ...

  ### WindowStyle Value:
      WindowStyle.Closable=2,
                 .Miniaturizable=1<<2,
                 .Resizable=1<<3,
                 .Titled=1,
                 .Typical=15,
                 .Utility=1<<4

  ### libAppKit Value:
      <CDLL 'AppKit.framework/AppKit', handle 7fff95603cc8 at 7fd6086924d0>

  ### libCF Value:
      <CDLL 'CoreFoundation.framework/CoreFoundation', handle 7fff956063c0 a
      t 7fd608680f10>

  ### libCG Value:
      <CDLL 'CoreGraphics.framework/CoreGraphics', handle 7fff956fc058 at 7f
      d608692a10>

  ### libCT Value:
      <CDLL 'CoreText.framework/CoreText', handle 7fff956002f8 at 7fd60869f7
      10>

  ### libFoundation Value:
      <CDLL 'Foundation.framework/Foundation', handle 7fff956018f0 at 7fd608
      69fcd0>

  ### libobjc Value:
      <CDLL 'libobjc.dylib', handle 7fff95605e4c at 7fd60869fc90>