[Pyobjc-dev] __getitem__objectForKey_ shadows __getitem__
Brought to you by:
ronaldoussoren
From: James R E. <Jam...@lr...> - 2009-10-09 12:47:03
|
Hi folks, I was trying to be smart in a class that provides both a Cocoa-style and Pythonic interface (i.e. implementing both objectForKey_ and __getitem__ and friends). It turns out that PyObjC already does that for me (cool!), but in the process of debugging an unrelated fault in my program, I noticed that the implementation in PyObjC will always replace __getitem__ with __getitem__objectForKey_, meaning that it is impossible to combine different lookup behaviors for the Objective-C and Pythonic interfaces. (I'm haven't yet convinced myself that this is necessarily a bad thing.) See the following example: >>> from Foundation import * >>> import objc >>> class Foo(NSObject): ... def objectForKey_(self, key): ... return 'object for key' ... def __getitem__(self, key): ... return 'getitem' ... >>> foo = Foo.alloc().init() >>> foo.objectForKey_('foo') 'object for key' >>> foo['foo'] 'object for key' >>> foo.__getitem__ <bound method Foo.__getitem__objectForKey_ of <Foo: 0x370e880>> From what I can tell, the relevant code is in pyobc-core/Lib/objc/ _convenience.py:88 : if sel in CONVENIENCE_METHODS: v = CONVENIENCE_METHODS[sel] for nm, value in v: if nm in type_dict and isinstance(type_dict[nm], selector): # Clone attributes of already existing version t = type_dict[nm] v = selector(value, selector=t.selector, signature=t.signature, isClassMethod=t.isClassMethod) type_dict[nm] = v else: type_dict[nm] = value This seems to be a fairly core portion of the PyObjC, and I have not explored the ramifications of modifying the inner if ... else block to only add the convenience methods if the nm is not already in type_dict. Should that else really be an "elif nm not in type_dict" ? Cheers! James |