ui factory - what should it do?
Jan Hudec
bulb at ucw.cz
Wed Feb 22 20:46:23 GMT 2006
On Wed, Feb 22, 2006 at 11:43:08 -0500, Aaron Bentley wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Martin Pool wrote:
> > In that particular case it's clearly working for only the duration of
> > __init__. (Which is perhaps not an ideal idiom; other job-type classes
> > have an explicit "do it" method, and perhaps we should standardize
> > that.)
>
> While it's a bit weird the first time you see it, it seems quite a handy
> way of doing it, and it's the way I did the TreeTransform mergers (e.g.
> Merge3Merger).
>
> Because if I were to convert fetcher to have a do-it method, I'd put the
> entire body of the __init__ method there. And then I'd have to restore
> the members to safe values afterward, so no unsafe member functions
> could be called.
>
> There is definitely a need for an idiom represent a procedure with
> multiple phases and shared data, where that shared data becomes obsolete
> at the end of the procedure, and this way didn't seem so bad, on reflection.
One can actually make a class behave exactly like a function in python. It
just takes a little fiddling with the metaclass.
Basically cls(arguments) expands to cls.__class__.__call__(arguments). If
cls.__class__ == type, that that method does roughly:
instance = cls.__new__(arguments)
instance.__init__(arguments)
return instance
But cls.__class__ does not have to be type:
class CallableMeta(type):
def __call__(self, *pa, **kwa):
inst = type.__call__(self)
return inst.run(*pa, **kwa)
class Callable(object):
__metaclass__ = CallableMeta
def run(arguments):
do_whatever_you_want_here
return any_appropriate_result
Actually, there is even simpler way -- you can simply put the code in
__new__. You just need to call super(...).__new__() to get the instance
(__new__ is a classmethod). But then __init__ will be called on whatever you
return -- which is OK for None, True, False, numbers and tuples, but not
other types.
I expect seasoned pythonists to reject this on basis of being dirty, but
TIMTOWDI even in languages that clame there is not ;-).
--
Jan 'Bulb' Hudec <bulb at ucw.cz>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : https://lists.ubuntu.com/archives/bazaar/attachments/20060222/8c33ff83/attachment.pgp
More information about the bazaar
mailing list