[Python-Dev] PEP 416: Add a frozendict builtin type (original) (raw)

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