On Wed, Jul 16, 2014 at 09:47:59AM -0400, R. David Murray wrote:
> It would be nice to be able to return a frozendict instead of having the
> overhead of building a new dict on each call.
There already is an in-between available both to Python and C:
PyDictProxy_New() / types.MappingProxyType. It's a one line change in
each case to return a temporary intermediary, using something like (C):
Py_INCREF(self->dict)
return self->dict;
To
return PyDictProxy_New(self->dict);
Or Python:
return self.dct
To
return types.MappingProxyType(self.dct)
Which is cheaper than a copy, and avoids having to audit every use of
self->dict to ensure the semantics required for a "frozendict" are
respected, i.e. no mutation occurs after the dict becomes visible to the
user, and potentially has __hash__ called.
> That by itself might not be enough reason. But, if the user wants to
> use the data in modified form elsewhere, they would then have to
> construct a new regular dict out of it, making the decision to vary
> the data from what matches the state of the object it came from an
> explicit one. That seems to fit the Python zen ("explicit is better
> than implicit").
>
> So I'm changing my mind, and do consider this a valid use case, even
> absent the crash.
Avoiding crashes seems a better use for a read-only proxy, rather than a
hashable immutable type.
David
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com