Re: [Pyobjc-dev] Headache over hacking an XML editor
Brought to you by:
ronaldoussoren
From: <bb...@ma...> - 2003-01-14 19:39:54
|
On Tuesday, Jan 14, 2003, at 14:24 US/Eastern, Just van Rossum wrote: > bb...@ma... wrote: > >>> self = cls.alloc() >>> self.release() # ownership transferred to the Python > wrapper >>> return self >> >> This code is lacking the call to the -init method -- problematic. > > I was thinking of this pattern, which is not 100% Pythonic, yet 100% > better than having to do a release() "by hand": > > inst = ASubclassOfNSObject().init() > > So basically "i = cls()" is equivalent to "i = cls.alloc(); > i.release()". There are cases where this will not work -- Ronald has already had to special case around a number of them. NSData, NSArray, and NSCell (I think) are examples. Not because of bugs in Foundation/AppKit, but because of the implementation pattern used. It would have to be something like.... i = cls.alloc() i.autorelease() ... anyway. (but won't work because of the reasons noted above) >> What about arguments to the constructor? We can handle the no >> argument case transparently, but what about-- say-- NSView's >> -initWithFrame: designated initializer? > > aView = NSView().initWithFrame(...) Makes sense. >> Also, keep in mind that -init* methods return an object reference for >> a reason; a number of intializers return a different instance than >> the one that was called for a number of [valid] reasons. > > Solved above ;-) Except manipulating the retain count on the return value from +alloc* leads to really nasty crashes (of which, some *are* bugs in the Foundation/AppKit -- Ronald has reported a couple, I believe). >>> This doesn't touch the alloc() semantics, yet provides a much more >>> Pythonic way to create instances. Heck, this will even call >>> __init__() for you! ;-) >> >> But __init__() is not generally the designated intiailizer for ObjC >> classes-- even Python implemented subclasses of ObjC classes. >> >> When subclassing ObjC from Python, it makes more sense to follow the >> ObjC semantics than the Python semantics -- at least, it does to me. > > Sure, but calling __init__ won't hurt either if you're writing an > NSObject subclass solely to be instantiated from Python. But I'm afraid > this behavior is implicit in the Python object protocol (since 2.2). I > _think_ it's this: > > inst = cls.__new__(cls, *args, **kwargs) > if isinstance(inst, cls): > inst.__init__(*args, **kwargs) > > (I also think it's identical for tp_new/tp_init on the C side.) True. And I'm all for anything that can make the Python side of the bridge more pythonic -- as long as it can be done consistently and without introducing instability. b.bum |