declaring multimethods [Was: Re: PEP 318]
Ville Vainio
ville at spammers.com
Wed Mar 24 14:58:16 EST 2004
Something just occured to me as far as multimethods go - would it be
beneficial for there to exist only one, global-all-the-way multimethod
dispatcher? This way declaring new multimethods in a module would
register themselves with the same global dispatcher that all the other
modules use. I.e.:
# module spam
def foo(x) [multimethod(str)]:
pass
# module eggs
import spam
def foo(x) [multimethod(int)]:
pass
foo("hello") # calls foo in 'spam'
This would improve opportunities for creating multimethod-driven
frameworks that could e.g. specify that 'validate_request' multimethod
will be called with all the requests received, so the user should implement
def validate_request(req) [multimethod(DisconnectRequest)]:
return True
if he chooses to acknowledge the request.
(I know this is a contorted example and better solutions already
exists, so no need to point it out).
The global-all-the-way approach seems a bit out of place in usually so
modular Python. It might be more desirable to provide utility
functions to choose a 'dispatcher-space', like this:
select_dispatcher("ultrawidget_multimethods")
# all the multimethod declarations now add their signatures to this
# dispatcher, and all the mm invocations search for signatures in this space
foo = import_multimethod("ultrawidget_multimethods", "foo")
# now you can call foo(42, "blah") without actually declaring a new
# multimethod in the current module. Otherwise the only way to bind
# 'foo' to the dispatcher would be declaring at least one multimethod.
In the modular, more Pythonic way, adding new multimethods to the same
dispatcher would require doing something like:
def foo(x) [multimethod_with_dispatcher(moduleb, str)]:
pass
where foo would be registered with the multimethod dispatcher of moduleb.
All this is probably too complicated or "different" to bundle in
stdlib (even in a hypothetical handy_demo_decorators module), but it
might be a fun third-party module for someone to hack. Even plain
one-module dispatching would be a useful demo.
--
Ville Vainio http://tinyurl.com/2prnb
More information about the Python-list
mailing list