[Python-Dev] PEP 416: Add a frozendict builtin type

Victor Stinner victor.stinner at haypocalc.com
Thu Mar 1 13:22:59 CET 2012


>> An immutable mapping can be implemented using frozendict::
>
>>     class immutabledict(frozendict):
>>         def __new__(cls, *args, **kw):
>>             # ensure that all values are immutable
>>             for key, value in itertools.chain(args, kw.items()):
>>                 if not isinstance(value, (int, float, complex, str, bytes)):
>>                     hash(value)
>>             # frozendict ensures that all keys are immutable
>>             return frozendict.__new__(cls, *args, **kw)
>
> What is the purpose of this?  Is it just a hashable frozendict?

It's an hashable frozendict or a "really frozen dict" or just "an
immutable dict". It helps to detect errors earlier when you need a
hashable frozendict. It is faster than hash(frozendict) because it
avoids to hash known immutable types.

If the recipe is confusion, it can be removed. Or it may be added to
collections or somewhere else.

> If it is for security (as some other messages suggest), then I don't
> think it really helps.
>
>    class Proxy:
>        def __eq__(self, other): return self.value == other
>        def __hash__(self): return hash(self.value)
>
> An instance of Proxy is hashable, and the hash is not object.hash,
> but it is still mutable.  You're welcome to call that buggy, but a
> secure sandbox will have to deal with much worse.

Your example looks to be incomplete: where does value come from? Is it
supposed to be a read-only view of an object?

Such Proxy class doesn't help to implement a sandbox because
Proxy.value can be modified. I use closures to implement proxies in
pysandbox. Dummy example:

def createLengthProxy(secret):
  class Proxy:
    def __len__(self):
      return len(secret)
  return Proxy()

Such proxy is not safe because it is possible to retrieve the secret:

secret = "abc"
value = createLengthProxy(secret).__len__.__closure__[0].cell_contents
assert value is secret

pysandbox implements other protections to block access to __closure__.

Victor


More information about the Python-Dev mailing list