[Python-ideas] Multiple dispatch (was Re: PEP 484 change proposal: Allowing <at> overload outside stub files
Guido van Rossum
guido at python.org
Sun Jan 24 00:37:17 EST 2016
On Sat, Jan 23, 2016 at 6:45 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> [...]
> There is one aspect that still requires runtime stack introspection
> [2], and that's getting access to the class scope in order to
> implicitly make method dispatch specific to the class defining the
> methods. It's the kind of thing that makes me wonder whether we should
> be exposing a thread-local variable somewhere with a "class namespace
> stack" that made it possible to:
>
> - tell that you're currently running in the context of a class definition
> - readily get access to the namespace of the innermost class currently
> being defined
I wonder if it wouldn't be acceptable to have a metaclass that takes
care of the dispatch registry. You'd have a metaclass whose
__prepare__ method produces a special kind of namespace that
collaborates with a @dispatch() decorator. In this design, @dispatch()
would not do the registration, it would just store its parameters on a
function attribute and mark the function (or return some other object
representing the dispatch parameters and the function). When the
namespace receives a __setattr__() call with such an object, it
registers it and if needed merges it with the object already there.
Admittedly, calling inspect.currentframe() and assuming it never
returns None is probably less code. (Hm, maybe sys._getframe() could
be guaranteed to work inside a class scope?)
> [1] http://multiple-dispatch.readthedocs.org/en/latest/design.html#namespaces-and-dispatch
> [2] https://github.com/mrocklin/multipledispatch/blob/master/multipledispatch/core.py
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list