Package pycocoa
[frames] | no frames]

Package pycocoa

A basic, partial, 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 original New BSD License and the MIT License.

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

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

The tests and examples have only been run with 64-bit Python 2.7.14 and 3.6.5 using Python-VLC 2.2.6, 3.0.1, 3.0.2 and 3.0.3 (with the compatible VLC App), but only on macOS 10.13.4 High Sierra. PyCocoa has not been tested on iOS nor with 32-bit Python and does not work using PyPy nor with Intel(R) Python.

All PyCocoa source code has been statically checked with PyChecker, PyFlakes, PyCodeStyle (formerly Pep8) and McCabe using 64-bit Python 2.7.14 and with Flake8 using 64-bit Python 3.6.5.

To install PyCocoa, type pip install PyCocoa or easy_install PyCocoa in a terminal window. Alternatively, download PyCocoa-X.Y.Z from PyPI or GitHub, unzip the downloaded file, cd to directory PyCocoa- and type python setup.py install. To run the PyCocoa tests, type python setup.py test before installation.

Some alternatives to PyCocoa are (a) PyObjC, the most comprehensive Python to Objective-C bridge, (b) Rubicon-ObjC for Python 3.5+, taking advantage of Python's new typing annotations and (c) PyGUI for macOS.

__

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.

__

Copyright (C) 2017-2018 -- mrJean1 at Gmail dot com

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.


Version: 18.06.10

Submodules

Classes
  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.
  CFIndex_t
  CFRange_t
ObjC struct with fields loc[ation] and len[gth] (both CFIndex_t).
  CFStr
Python wrapper for the ObjC CFString class, creating retained instances, by default.
  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).
  CTFontOrientation_t
  CTFontSymbolicTraits_t
  Class_t
ObjC Class type, encoding b'#'.
  Data_t
  Dict
Python dict Type, wrapping an ObjC NSMutableDictionary.
  Dictionary_t
  ErrorPanel
Python Type to show an NSError alert, wrapping ObjC NSAlert.
  Font
Python Font Type, wrapping ObjC NSFont.
  FontError
Font selection error.
  FontTraitError
Font traits error.
  FrozenDict
Python immutable dict Type, wrapping an (immutable) ObjC NSDictionary.
  FrozenSet
Python frozenset Type, wrapping an immutable ObjC NSSet.
  IMP_t
ObjC IMPlementation type.
  Id_t
ObjC Id/self type, encoding b'@'.
  Item
Python menu Item Type, wrapping ObjC NSMenuItem.
  Ivar_t
ObjC instance variable type.
  List
Python list Type, wrapping an ObjC NSMutableArray.
  MediaWindow
Media window Python Type, wrapping ObjC NSWindow/NSView.
  Menu
Menu Python Type, wrapping ObjC NSMenu.
  MenuBar
Python MenuBar Type, wrapping ObjC NSMenu.
  Method_t
ObjC method type.
  NSDecimal
Optimized, Python NSDecimalNumber class.
  NSDouble_t
  NSExceptionHandler_t
  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 NSString class, creating auto-released instances, by default.
  NSTimeInterval_t
  NSUInteger_t
  NumberType_t
  Number_t
  ObjCBase
Base class for Python runtime.ObjC... classes.
  ObjCBoundClassMethod
Only to distinguish bound class- from bound instance-methods.
  ObjCBoundMethod
Python wrapper for an ObjC class or instance method, an IMP_t.
  ObjCClass
Python wrapper for an ObjC class.
  ObjCClassMethod
Only to distinguish class methods from instance methods.
  ObjCInstance
Python wrapper for an ObjC instance.
  ObjCMethod
Python class representing an unbound ObjC class- or 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
  Point
Python Type, wrapping an ObjC NSPoint_t.
  Point2
Python Type, like Point, different signature.
  Protocol_t
ObjC protocol type.
  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.
  Separator
Python menu Separator Type, wrapping ObjC NSMenuItem.separatorItem.
  Set
Python c{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 Type table of rows and columns, 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
  Tuple
Python tuple Type, wrapping an immutable ObjC NSArray.
  TypeCodeError
Error in ObjC type encoding.
  TypeID_t
  TypeRef_t
ObjC opaque type.
  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.
  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.
 
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)
Compute the smallest, int 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 like repr(bytestr).
 
bytes2str(bytestr, dflt=missing())
Convert bytes/unicode to str if needed.
 
clip(bytestr, limit=50)
Clip a string or bytes to the given length limit.
 
closeTables()
Close all tables.
 
dict2NS(py, frozen=False)
Create an NSMutableDictionary instance from a Python dict.
 
flint(f)
Return int for integer float.
 
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.
 
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(obj, dflt=missing())
Get the name of the ObjC class of an object.
 
get_classof(obj)
Get the ObjC class of an object.
 
get_inheritance(clas)
Yield the inheritance of an ObjC class.
 
get_ivar(obj, 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_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_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_selector(name_)
Get an ObjC selector by 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(obj, dflt=missing())
Get the name of the ObjC super-class of an object.
 
get_superclassof(obj)
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(obj)
Check whether an object is an ObjC clas.
 
isImmutable(obj, mutableClass, immutableClass, name='ns')
Check that an Obj object is an instance of the immutable class.
 
isInstanceOf(obj, *Classes, **name_missing)
Check whether an ObjC object is an instance of some ObjC class.
 
isLink(path)
Resolve a file or folder link or alias.
 
isMetaClass(obj)
Check whether an object is an ObjC metaclass.
 
isNone(obj)
Return True if obj is None, NSMain.nil, NSMain.Null, etc.
 
isinstanceOf(inst, *classes, **name_missing)
Check a Python object's class.
iterator
iterbytes(collection)
iter(callable, sentinel) -> iterator
 
leaked2()
Return the number of memory leaks.
 
list2NS(py)
Create an NSMutableArray instance from a Python list.
 
map2NS(py)
Create an NSArray instance from a Python map.
 
ns2App(ns)
Get the App instance from an NSApplication or an NSNotification instance.
 
ns2Item(ns)
Get the Item instance for an NSMenuItem.
 
ns2Type(ns)
Convert an NS... ObjC object to an instance of the corresponding Python Type and value.
 
ns2Window(ns)
Get the Window instance for an ObjC NSWindow or NSNotification instance.
 
ns2py(ns, dflt=None)
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.
 
nsBoolean2bool(ns, dflt=missing())
Create a Python bool from an NSBoolean.
 
nsBundleRename(nsTitle, match='Python')
Change the bundle title if the current title matches.
 
nsData2bytes(ns, dflt='')
Create Python bytes from NSData.
 
nsDeallocObserver(objc)
Create a de-allocation observer for an ObjC instance.
 
nsDecimal2decimal(ns)
Create a Python Decimal from an NSDecimalNumber.
 
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.
 
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.
 
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(ns_exception)
Mimick ObjC's @throw NSException to raise an exception.
 
nsUncaughtExceptionHandler(handler)
Install an ObjC NSException handler, the handler signature must match NSExceptionHandler_t def handler(ns_exc): ....
 
printf(fmt, *args, **kwds)
Formatted print fmt % args with optional keywords.
 
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.
 
send_message(receiver, name_, *args, **resargtypes)
Send message to an ObjC object.
 
send_super(receiver, name_, *args, **resargtypes)
Send message to the super-class of an ObjC object.
 
set2NS(py)
Create an NSMutableSet instance from a Python set.
 
set_ivar(obj, name, value, ctype=None)
Set an instance variable of an ObjC object.
 
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, auto=True)
Create an NSStr instance from a Python str.
 
str2bytes(bytestr, dflt=missing())
Convert str to bytes/unicode if needed.
 
title2action(title)
Convert a menu item title to a valid 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'>)
Return a Python Type instance as str or repr.
 
unicode2NS(py, auto=True)
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 value to string with 1_000's seperator.
 
zSIstr(size, B='B')
Convert a size value to string with SI-units.
Variables
  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}'
  DEFAULT_UNICODE = 'utf-8'
  FontTrait = FontTrait.Bold...
  Fonts = Fonts.App=Font(name='Helvetica', family='Helvetica', s...
  NO = False
  NSAlert = ObjCClass('NSAlert')
  NSAlphaShiftKeyMask = 65536
  NSAlternateKeyMask = 524288
  NSAnyEventMask = 4294967295
  NSApplication = ObjCClass('NSApplication')
  NSApplicationActivationPolicyAccessory = 1
  NSApplicationActivationPolicyProhibited = 2
  NSApplicationActivationPolicyRegular = 0
  NSApplicationDefined = 15
  NSApplicationDelegate = ObjCClass('_NSApplicationDelegate')
  NSApplicationDidHideNotification = c_void_p(140735562117056)
  NSApplicationDidUnhideNotification = c_void_p(140735562117152)
  NSApplicationPresentationDefault = 0
  NSApplicationPresentationDisableHideApplication = 256
  NSApplicationPresentationDisableProcessSwitching = 32
  NSApplicationPresentationHideDock = 2
  NSApplicationPresentationHideMenuBar = 8
  NSArray = ObjCClass('NSArray')
  NSAttributedString = ObjCClass('NSAttributedString')
  NSAutoreleasePool = ObjCClass('NSAutoreleasePool')
  NSBackingStoreBuffered = 2
  NSBackingStoreNonretained = 1
  NSBackingStoreRetained = 0
  NSBeginFunctionKey = 63274
  NSBezierPath = ObjCClass('NSBezierPath')
  NSBoolean = NSNumber.numberWithBool_
  NSBundle = ObjCClass('NSBundle')
  NSCancelButton = 0
  NSCenterTextAlignment = 2
  NSColor = ObjCClass('NSColor')
  NSCommandKeyMask = 1048576
  NSConcreteNotification = ObjCClass('NSConcreteNotification')
  NSConstantString = ObjCClass('NSConstantString')
  NSControlKeyMask = 262144
  NSData = ObjCClass('NSData')
  NSDecimalNumber = ObjCClass('NSDecimalNumber')
  NSDefaultRunLoopMode = c_void_p(140735571296632)
  NSDeleteFunctionKey = 63272
  NSDictionary = ObjCClass('NSDictionary')
  NSDockTile = ObjCClass('NSDockTile')
  NSDouble = NSNumber.numberWithDouble_
  NSEndFunctionKey = 63275
  NSEnumerator = ObjCClass('NSEnumerator')
  NSError = ObjCClass('NSError')
  NSEventTrackingRunLoopMode = c_void_p(140735562111744)
  NSException = ObjCClass('NSException')
  NSFileHandlingPanelCancelButton = 0
  NSFileHandlingPanelOKButton = 1
  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
  NSFunctionKeyMask = 8388608
  NSHelpKeyMask = 4194304
  NSHomeFunctionKey = 63273
  NSImage = ObjCClass('NSImage')
  NSInsertFunctionKey = 63271
  NSInt = NSNumber.numberWithInt_
  NSIntegerEncoding = 'l'
  NSIntegerMax = 9223372036854775807
  NSJustifiedTextAlignment = 3
  NSKeyDown = 10
  NSKeyUp = 11
  NSLayoutManager = ObjCClass('NSLayoutManager')
  NSLeftTextAlignment = 0
  NSLong = NSNumber.numberWithLong_
  NSLongLong = NSNumber.numberWithLongLong_
  NSMain = NSMain.Application=NSApplication(<Id_t at 0x106da8f80...
  NSMenu = ObjCClass('NSMenu')
  NSMenuItem = ObjCClass('NSMenuItem')
  NSMutableArray = ObjCClass('NSMutableArray')
  NSMutableData = ObjCClass('NSMutableData')
  NSMutableDictionary = ObjCClass('NSMutableDictionary')
  NSMutableSet = ObjCClass('NSMutableSet')
  NSMutableString = ObjCClass('NSMutableString')
  NSNaturalTextAlignment = 4
  NSNotFound = 9223372036854775807
  NSNotification = ObjCClass('NSNotification')
  NSNotificationCenter = ObjCClass('NSNotificationCenter')
  NSNull = ObjCClass('NSNull')
  NSNumber = ObjCClass('NSNumber')
  NSNumericPadKeyMask = 2097152
  NSOKButton = 1
  NSObject = ObjCClass('NSObject')
  NSOpenPanel = ObjCClass('NSOpenPanel')
  NSPageDownFunctionKey = 63277
  NSPageLayout = ObjCClass('NSPageLayout')
  NSPageUpFunctionKey = 63276
  NSPointEncoding = '{CGPoint=dd}'
  NSPointZero = NSPoint_t(0, 0)
  NSPrintInfo = ObjCClass('NSPrintInfo')
  NSPrintOperation = ObjCClass('NSPrintOperation')
  NSPrintPanel = ObjCClass('NSPrintPanel')
  NSPrinter = ObjCClass('NSPrinter')
  NSRangeEncoding = '{_NSRange=QQ}'
  NSRectEncoding = '{CGRect={CGPoint=dd}{CGSize=dd}}'
  NSRightTextAlignment = 1
  NSSavePanel = ObjCClass('NSSavePanel')
  NSScreen = ObjCClass('NSScreen')
  NSScrollView = ObjCClass('NSScrollView')
  NSSet = ObjCClass('NSSet')
  NSShiftKeyMask = 131072
  NSSizeEncoding = '{CGSize=dd}'
  NSSquareStatusItemLength = -2
  NSStatusBar = ObjCClass('NSStatusBar')
  NSString = ObjCClass('NSString')
  NSTableColumn = ObjCClass('NSTableColumn')
  NSTableView = ObjCClass('NSTableView')
  NSTableViewDashedHorizontalGridLineMask = 8
  NSTableViewDelegate = ObjCClass('_NSTableViewDelegate', 'NSTab...
  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')
  NSVariableStatusItemLength = -1
  NSView = ObjCClass('NSView')
  NSWindow = ObjCClass('NSWindow')
  NSWindowCloseButton = 0
  NSWindowDelegate = ObjCClass('_NSWindowDelegate')
  NSWindowDocumentIconButton = 4
  NSWindowMiniaturizeButton = 1
  NSWindowStyleMaskClosable = 2
  NSWindowStyleMaskMiniaturizable = 4
  NSWindowStyleMaskResizable = 8
  NSWindowStyleMaskTitled = 1
  NSWindowStyleMaskUsual = 15
  NSWindowStyleMaskUtilityWindow = 16
  NSWindowToolbarButton = 3
  NSWindowZoomButton = 2
  NSZoneEncoding = '{_NSZone=}'
  OBJC_ASSOCIATION_COPY = 771
  OBJC_ASSOCIATION_COPY_NONATOMIC = 3
  OBJC_ASSOCIATION_RETAIN = 769
  OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1
  PanelButton = PanelButton.Cancel...
  PyObjectEncoding = '{PyObject=@}'
  WindowStyle = WindowStyle.Closable...
  YES = True
  libAppKit = <CDLL '/System/Library/Frameworks/AppKit.framework...
  libCF = <CDLL '/System/Library/Frameworks/CoreFoundation.frame...
  libCT = <CDLL '/System/Library/Frameworks/CoreText.framework/C...
  libFoundation = <CDLL '/System/Library/Frameworks/Foundation.f...
  libobjc = <CDLL '/usr/lib/libobjc.dylib', handle 1001e3680 at ...
  libquartz = <CDLL '/System/Library/Frameworks/quartz.framework...
  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.

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:

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 ivars 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)

 

Compute the smallest, int aspect ratio.

Parameters:
  • width - The width (float or int).
  • height - The height (float or int).
Returns:
2-Tuple (width, height) 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:

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 like repr(bytestr).

Parameters:
  • bytestr - Str or bytes.
Returns:
Representation b'...' (str).

bytes2str(bytestr, dflt=missing())

 

Convert bytes/unicode to str if needed.

Parameters:
  • bytestr - Bytes, str or unicode.
  • dflt - Optional, default return value.
Returns:
Str or dflt.
Raises:
  • TypeError - If neither str nor bytes, but iff no dflt is provided.

clip(bytestr, limit=50)

 

Clip a string or bytes to the given length limit.

Parameters:
  • bytestr - Bytes or str.
  • limit - Length limit (int).
Returns:
Bytes or str.

dict2NS(py, frozen=False)

 

Create an NSMutableDictionary instance from a Python dict.

Parameters:
  • py - The value (dict).
  • frozen - Immutable (bool), mutable otherwise.
Returns:
The ObjC instance (NSMutableDictionary).
Raises:
  • RuntimeError - If len vs count assertion failed.

fontTraits(*traits)

 

Return a font traits mask for the named traits.

Parameters:
  • traits - Trait names (strs), case-insensitive.
Returns:
Combined traits (FontTraits mask).
Raises:

fontTraitstrs(traits)

 

Return font traits as names.

Parameters:
  • traits - Traits (FontTraits mask).
Returns:
Tuple of trait names (strs).

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.

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 arrays, bitfields, arbitrary structs and unions. 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:
Returns:
The class name (str).
Raises:
  • ValueError - Invalid clas, iff no dflt provided.

get_classnameof(obj, dflt=missing())

 

Get the name of the ObjC class of an object.

Parameters:
  • obj - The object (Object or Id_t).
Returns:
The object's class name (str).
Raises:
  • ValueError - Invalid obj, iff no dflt provided.

get_classof(obj)

 

Get the ObjC class of an object.

Parameters:
  • obj - 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:
Returns:
The parent classes (Class_t), in bottom-up order.

get_ivar(obj, name, ctype=None)

 

Get the value of an instance variable (ivar).

Parameters:
  • obj - 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 file name.

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_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_selector(name_)

 

Get an ObjC selector by name.

Parameters:
  • name_ - The selector name (str).
Returns:
The selector (SEL_t) if found, None otherwise.

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:
Returns:
The super-class (Class_t), None otherwise.

get_superclassnameof(obj, dflt=missing())

 

Get the name of the ObjC super-class of an object.

Parameters:
  • obj - The object (Object or Id_t).
Returns:
The object'ssuper-class name (str).
Raises:
  • ValueError - Invalid obj, iff no dflt provided.

get_superclassof(obj)

 

Get the ObjC super-class of an object.

Parameters:
  • obj - 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:
Returns:
The alias' target (str) or None if path isn't a macOS alias.

See Also: mac-alias and here.

isClass(obj)

 

Check whether an object is an ObjC clas.

Parameters:
  • obj - Object to check (Object or Class).
Returns:
True if the obj is a clas, False otherwise.

isImmutable(obj, mutableClass, immutableClass, name='ns')

 

Check that an Obj object is an instance of the immutable class.

Parameters:
  • obj - 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 obj is an immutableClass instance, False otherwise.
Raises:
  • TypeError - If obj is a mutableClass instance, provided keyword argument name='...' is given.

isInstanceOf(obj, *Classes, **name_missing)

 

Check whether an ObjC object is an instance of some ObjC class.

Parameters:
  • obj - 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 obj is not an ObjCInstance or c_void_p or if obj does not match any of the Classes and only if keyword name='...' is provided.

See Also: Function isinstanceOf for checking Python instances.

isLink(path)

 

Resolve a file or folder link or alias.

Parameters:
  • path - The link or alias name (str).
Returns:
The link's or alias' target (str) or None if path isn't a link or alias.

isMetaClass(obj)

 

Check whether an object is an ObjC metaclass.

Parameters:
  • obj - Object to check (Object or Class).
Returns:
True if the obj is a metaclass, False otherwise.

isNone(obj)

 

Return True if obj is None, NSMain.nil, NSMain.Null, etc.

Parameters:
Returns:
True or False (bool).

isinstanceOf(inst, *classes, **name_missing)

 

Check a Python object's 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 isInstanceOf 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.

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.

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 Item instance for an NSMenuItem.

Parameters:
  • ns - The ObjC instance (NSMenuItem).
Returns:
The item instance (Item).
Raises:
  • TypeError - Invalid ns type.

ns2Type(ns)

 

Convert an NS... ObjC object to an instance of the corresponding Python Type and value.

Parameters:
Returns:
The value (Python Type).

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=None)

 

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 (None).
Returns:
The value (Python type) or dflt.
Raises:
  • TypeError - Unhandled, unexpected TypeID.

Note: Conversion map:

  • NSArray -> tuple
  • NSBoolean -> bool
  • NSData -> bytes
  • NSDecimalNumber -> Decimal
  • NSDictionary -> dict
  • NSMutableArray -> list
  • NSMutableSet -> set
  • NSMutableString -> str
  • NSNumber -> int or float
  • NSNull -> None
  • NSSet -> frozenset
  • NSString -> str
  • NSStr/CFStr -> str

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).

nsBoolean2bool(ns, dflt=missing())

 

Create a Python bool from an NSBoolean.

Parameters:
Returns:
The bool (bool) of dlft.
Raises:
  • TypeError - Unexpected NumberType.

nsBundleRename(nsTitle, match='Python')

 

Change the bundle title if the current title matches.

Parameters:
  • nsTitle - 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_(nsTitle), the name of an App shown in the menu bar.

nsData2bytes(ns, dflt='')

 

Create Python bytes from NSData.

Parameters:
Returns:
The bytes (bytes) or dflt.

nsDeallocObserver(objc)

 

Create a de-allocation observer for an ObjC instance.

Parameters:
Returns:
The observer (_NSDeallocObserver).

Note: When the observed ObjC object is de-allocated, the _NSDeallocObserver removes the corresponding ObjCInstance from the dictionary of cached objects ObjCInstance._objc_cache_, effectively destroying the ObjCInstance.

nsDecimal2decimal(ns)

 

Create a Python Decimal from an NSDecimalNumber.

Parameters:
Returns:
The decimal (Decimal).
Raises:

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 (dict).

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.

nsLogf(fmt, *args)

 

Formatted write to the console.

Parameters:
  • fmt - A printf-like format string (str).
  • args - Optional arguments to format (all positional).

nsNull2none(ns)

 

Return Python None for an NS/CFNull or nil.

Parameters:
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:
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:
Returns:
The .NS object (NS...).
Raises:
  • TypeError - No .NS for this inst.

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:
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 lineseparators.
  • 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(ns_exception)

 

Mimick ObjC's @throw NSException to raise an exception.

Parameters:

nsUncaughtExceptionHandler(handler)

 

Install an ObjC NSException handler, the handler signature must match NSExceptionHandler_t def handler(ns_exc): ....

Parameters:
Returns:
Previously installed handler (NSExceptionHandler_t).

Note: Faults like SIGILL, SIGSEGV, etc. do not throw uncaught NSExceptions and will not invoke this handler.

printf(fmt, *args, **kwds)

 

Formatted print fmt % args with optional keywords.

Parameters:
  • fmt - Print-like format (str).
  • args - Optional arguments to include (all positional).
  • argv0 - Optional prefix (str).
  • nl - Number of leading blank lines (int).
  • nt - Number of trailing blank lines (int).

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

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: nsDeallocObserver below.

send_message(receiver, name_, *args, **resargtypes)

 

Send message to an ObjC object.

Parameters:
  • receiver - The recipient (Object).
  • name_ - Message selector (str).
  • args - Message arguments (all positional).
  • resargtypes - Optional, result and argument types (ctypes).
Returns:
Message result (restype).
Raises:
  • ArgumentError - Invalid receiver, name, args or resargtypes.
  • TypeError - Invalid receiver, name, args or resargtypes type.

Note: By default, the result and all 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(receiver, name_, *args, **resargtypes)

 

Send message to the super-class of an ObjC object.

Parameters:
  • receiver - The recipient (Object).
  • name_ - Message selector (str).
  • args - Message arguments (all positional).
  • resargtypes - Optional, result and argument types (ctypes).
Returns:
Message result (restype).
Raises:
  • ArgumentError - Invalid receiver, name, args or resargtypes.
  • TypeError - Invalid receiver, name, args or resargtypes type.

Note: By default, the result and all 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).

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.

set_ivar(obj, name, value, ctype=None)

 

Set an instance variable of an ObjC object.

Parameters:
  • obj - 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:

Note: Does not handle bitfields, arrays, structs, unions, 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 bitfields, arrays, structs, unions, etc. and strips any offset, size or width specifiers from the encoding.

Returns:
The individual type encodings (list).
Raises:

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, auto=True)

 

Create an NSStr instance from a Python str.

Parameters:
  • py - The value (str).
  • auto - Retain or auto-release (bool).
Returns:
The ObjC instance (NSStr).

str2bytes(bytestr, dflt=missing())

 

Convert str to bytes/unicode if needed.

Parameters:
  • bytestr - Bytes, str or unicode.
  • dflt - Optional, default return value.
Returns:
Bytes or dflt.
Raises:
  • TypeError - If neither bytes nor str, but iff no dflt is provided.

title2action(title)

 

Convert a menu item title to a valid callback method name.

Parameters:
  • title - The item's title (str).
Returns:
Name for the callback method (str).
Raises:
  • ValueError - Invalid method name for this title.

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'>)

 

Return a Python Type instance as str or repr.

Parameters:
  • inst - Instance (any).
  • strepr - Conversion (repr or str).
Returns:
Instance representation (str).

unicode2NS(py, auto=True)

 

Create an NSStr instance from a Python unicode string.

Parameters:
  • py - The value (unicode).
  • auto - Retain or auto-release (bool).
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:

z1000str(size, sep='_')

 

Convert a size value to string with 1_000's seperator.

Parameters:
  • size - Value to convert (float or int).
Returns:
"<1or2digits><sep><3digits>..." or "-" if size is negative (str).

zSIstr(size, B='B')

 

Convert a size value to string with SI-units.

Parameters:
  • size - Value to convert (float or int).
Returns:
"<Size> <B><SI>" (str).

Variables Details

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,
          .RoundRect=3<<2,
          .Rounded=1,
...

Border

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

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(name='Helvetica', family='Helvetica', size=12, weight=5\
),
     .Bold=Font(name='.SFNSText-Bold', family='.SF NS Text', size=13, \
traits='Bold', weight=9),
     .BoldItalic=Font(name='.SFNSText-BoldItalic', family='.SF NS Text\
', size=13, traits='Bold Italic', weight=9),
     .Italic=Font(name='.SFNSText-Italic', family='.SF NS Text', size=\
13, traits='Italic', weight=5),
...

NSMain

Value:
NSMain.Application=NSApplication(<Id_t at 0x106da8f80>) of 0x106139350\
,
      .BooleanNO=NSBoolean(<Id_t at 0x106da8170>) of 0x7fff8dcb63f8,
      .BooleanYES=NSBoolean(<Id_t at 0x106d9dcb0>) of 0x7fff8dcb63e8,
      .Bundle=NSBundle(<Id_t at 0x106d9d950>) of 0x1054109c0,
      .BundleName=NSConstantString('CFBundleName'),
      .FontManager=NSFontManager(<Id_t at 0x106b9eef0>) of 0x106114c90\
,
...

NSTableViewDelegate

Value:
ObjCClass('_NSTableViewDelegate', 'NSTableViewDataSource')

PanelButton

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

WindowStyle

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

libAppKit

Value:
<CDLL '/System/Library/Frameworks/AppKit.framework/AppKit', handle 102\
091940 at 1030d3450>

libCF

Value:
<CDLL '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundat\
ion', handle 1001e1800 at 1026aa8d0>

libCT

Value:
<CDLL '/System/Library/Frameworks/CoreText.framework/CoreText', handle\
 1020606f0 at 1030e05d0>

libFoundation

Value:
<CDLL '/System/Library/Frameworks/Foundation.framework/Foundation', ha\
ndle 10053d590 at 1030e0c10>

libobjc

Value:
<CDLL '/usr/lib/libobjc.dylib', handle 1001e3680 at 1030e0a50>

libquartz

Value:
<CDLL '/System/Library/Frameworks/quartz.framework/quartz', handle 102\
069590 at 1030d3690>