Commits

Ronald Oussoren  committed f4e922c

Add implementation of NSDictionaryOfVariableBindings

This adds a trivial implementation of NSDictionaryOfVariableBindings. The
difference with ObjC is that the arguments are strings, not identifiers. The
latter cannot be implemented in Python.

Fixes issue #8

  • Participants
  • Parent commits 1af4964

Comments (0)

Files changed (3)

File pyobjc-framework-Cocoa/Doc/api-notes-AppKit.txt

 
     { "button1": button1, "button2": button2 }
 
+or::
 
-Note: it is possible to implement this macro as a Python function with a slightly different
-API: pass the variable names as strings instead of identifiers.
+    AppKit.NSDictionaryOfVariableBindings("button1", "button2")
+
+The first alternative is preferable because it is cleaner Python code, and
+the implementation of ``NSDictionaryOfVariableBindings`` has to use an
+unstable API of CPython.

File pyobjc-framework-Cocoa/Lib/AppKit/__init__.py

 from AppKit import _metadata
 from AppKit._inlines import _inline_list_
 
+def NSDictionaryOfVariableBindings(*names):
+    """
+    Return a dictionary with the given names and there values.
+    """
+    import sys
+    variables = sys._getframe(1).f_locals
+
+    return {
+        nm: variables[nm] 
+        for nm in names 
+    }
+
 
 sys.modules['AppKit'] = mod = objc.ObjCLazyModule('AppKit',
         "com.apple.AppKit", objc.pathForFramework("/System/Library/Frameworks/AppKit.framework"),
         _metadata.__dict__, _inline_list_, {
             '__doc__': __doc__,
             'objc': objc,
+            'NSDictionaryOfVariableBindings': NSDictionaryOfVariableBindings,
             '__path__': __path__,
         }, (Foundation,))
 

File pyobjc-framework-Cocoa/PyObjCTest/test_nslayoutcontraint.py

+from PyObjCTools.TestSupport import *
+from AppKit import *
+
+class TestNSLayoutContraintManual (TestCase):
+    def testNSDictionaryOfVariableBindings(self):
+        var1 = 'foo'
+        var2 = 'bar'
+
+        self.assertEqual(NSDictionaryOfVariableBindings('var1', 'var2'),
+                {'var1': 'foo', 'var2': 'bar'})
+
+        self.assertRaises(KeyError, NSDictionaryOfVariableBindings, 'var1', 'var3')
+if __name__ == "__main__":
+    main()