[Python-ideas] A bind protocol (was Re: New __reference__ hook)
Eric Snow
ericsnowcurrently at gmail.com
Wed Dec 5 20:42:41 CET 2012
On Wed, Dec 5, 2012 at 11:09 AM, Sturla Molden <sturla at molden.no> wrote:
> But apart from that, I think allowing overloading of the binding operator
> "=" might be a good idea. A special method __bind__ could return the object
> to be bound:
>
> a = b
>
> should then bind the name "a" to the return value of
>
> b.__bind__()
>
> if b implements __bind__.
Keep in mind that descriptors already give you that for classes.
There are other workarounds if you *really* have to have this
functionality. You're right that globals (module body namespace) and
locals (function body namespace) do not have that capability[1].
The main case I've heard for a generic "bind" protocol is for DRY.
For instance, you create a new object with some name as an argument
and then bind that object to that name in the current running
namespace. This has been brought up before[2], with the canonical
example of namedtuple (along with arguments on why it's not a big
deal[3]).
I'd expect such an API to look something like this:
object.__bind__(name, namespace)
object.__unbind__(name, namespace, replacement=None)
namespace is the mapping for the locals/object (a.k.a. vars()) where
the name is going to be bound. When an object is already bound to a
name, __unbind__() would be called first on the current object. In
that case, replacement would be the object that is replacing the
currently bound one. At a high level the whole binding operation
would look something like this:
def bind(ns, name, obj):
if name in ns:
ns[name].__unbind__(name, ns, obj)
obj.__bind__(name, ns)
ns[name] = obj # or whatever
If you wanted to get fancy, both methods could return a boolean
indicating that the name should *not* be bound/unbound (respectively):
def bind(ns, name, obj):
if name in ns:
if not ns[name].__unbind__(name, ns, obj):
return
if obj.__bind__(name, ns):
ns[name] = obj # or whatever
The bind protocol could also be used in the fallback behavior of
augmented assignment operations.
Ultimately, considering how often things are bound/unbound, I'd worry
that it would be too expensive for any bind API to see the light of
day.
-eric
[1] You *can* use your own module class to get it for "globals", sort
of. This wouldn't quite work for the globals associated with
functions defined in the module.
[2] http://mail.python.org/pipermail/python-ideas/2011-March/009233.html,
and others.
[3] http://mail.python.org/pipermail/python-ideas/2011-March/009277.html
More information about the Python-ideas
mailing list