GithubHelp home page GithubHelp logo

python-frozendict's Introduction

frozendict

frozendict is an immutable wrapper around dictionaries that implements the complete mapping interface. It can be used as a drop-in replacement for dictionaries where immutability is desired.

Of course, this is python, and you can still poke around the object's internals if you want.

The frozendict constructor mimics dict, and all of the expected interfaces (iter, len, repr, hash, getitem) are provided. Note that a frozendict does not guarantee the immutability of its values, so the utility of hash method is restricted by usage.

The only difference is that the copy() method of frozendict takes variable keyword arguments, which will be present as key/value pairs in the new, immutable copy.

Example shell usage:

from frozendict import frozendict

fd = frozendict({ 'hello': 'World' })

print fd
# <frozendict {'hello': 'World'}>

print fd['hello']
# 'World'

print fd.copy(another='key/value')
# <frozendict {'hello': 'World', 'another': 'key/value'}>

python-frozendict's People

Contributors

eugene-eeo avatar jaraco avatar jbarberu avatar lurch avatar pasztorpisti avatar ppolewicz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-frozendict's Issues

Repr implementation should eval

All builtin types have a __repr__ implementation that can be fed to eval to obtain the original Python value. This is on purpose. frozendict and OrderedFrozendict simply being an immutable version of builtin types should also support this behavior. One simply need to slightly modify the __repr__ implementation.

def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self._dict)

This parallels frozenset's __repr__.

Possible memory leak with Python 3.9

When frozendict is converted to string in python 3.9, it causes allocations of memory which can not be released with gc.collect()

import gc
import psutil
from frozendict import frozendict


def rss():
    return psutil.Process().memory_info().rss


def process(body):
    str(body)


if __name__ == '__main__':
    initial_memory = rss()
    for i in range(100000):
        payload = frozendict({"text": "Hello", "category": "electronics", "keyword": "electronics"})
        # payload = {"text": "Hello", "category": "electronics", "keyword": "electronics"}
        process(payload)

    print("memory before: ", initial_memory)
    gc.collect()
    print("memory after:  ", rss())

Result with frozendict

memory before:  13094912
memory after:   27693056

Result with builtin dictionary

memory before:  13086720
memory after:   13086720

Thoughts on modifiable_copy?

from frozendict import frozendict
a = frozendict({'a': 1})
b = a.copy()
b['c'] = 1

throws the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'frozendict' object does not support item assignment

However, a common usage in my program is to copy over the unmodifiable frozendict to another place and do some modification. I wonder if we can provide a method called modifiable_copy such that

from frozendict import frozendict
a = frozendict({'a': 1})
b = a.modifiable_copy()
b['c'] = 1

is allowed

Nested dicts are not supported

Can nested dictionaries be supported? Is this a bug or expected behavior to only support shallow dictionaries?

def test_frozen_dicts():
    orig_sub = {'subkey': 'sA'}
    orig_top = {'topkey': 'tA', 'child': orig_sub}

    frozen = frozendict(orig_top)
    print(f"before: {frozen}")

    orig_top['topkey'] = 'tB'
    orig_sub['subkey'] = 'sB'
    print(f"after: {frozen}")
>>> test_frozen_dicts()
before: <frozendict {'topkey': 'tA', 'child': {'subkey': 'sA'}}>
after: <frozendict {'topkey': 'tA', 'child': {'subkey': 'sB'}}>

Expected: All nested dictionaries are also frozen.

Thanks.

Incompatible with Python>=3.10 (AttributeError: module 'collections' has no attribute 'Mapping')

Issue: error thrown on module import

>>> import frozendict
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/crypt0xyc/projects/starknet-arb/.venv/lib/python3.10/site-packages/frozendict/__init__.py", line 16, in <module>
    class frozendict(collections.Mapping):
AttributeError: module 'collections' has no attribute 'Mapping'

Proposed solution for Python 3.10 compatibility
replace collections.Mapping with collections.abc.Mapping

version information

Programmatic version information is missing.

import frozendict
frozendict.__version__

Frozendict is broken on Python 3.8, warns on 3.7

Closing because this repo is abandoned in favor of https://github.com/Marco-Sulla/python-frozendict


Hi! FYI, the following line is emitting deprecation warnings, and will break on Python 3.8:

class frozendict(collections.Mapping):

That's because all of the abstract base classes have been moved from collections in Python 2, to collections.abc in Python 3. The warning was added in python/cpython#5460. Could you try to import from collections.abc and fall back to the existing style?

Generics?

In code using PEP 484, it would be nice to be able to do this:

def spam() -> FrozenDict[Text, int]):
  return frozendict({'eggs': 1})

The CamelCase name is chosen to mirror typing.FrozenSet et al. I think you can sort of use typing.Mapping[A, B] instead if you need generics, but it's not as specific.

installs under Python 3, but doesn't work

Hi,

frozendict doesn't work in Python 3. The first problem I find is

Traceback (most recent call last):
  File "./MC_experiment.py", line 13, in <module>
    items = set(random.sample(items, 1000))
  File "/usr/local/lib/python3.4/dist-packages/frozendict/__init__.py", line 26, in __hash__
    self.__hash = reduce(operator.xor, map(hash, self.iteritems()), 0)
NameError: name 'reduce' is not defined

(of course fixing this one should be trivial)

Is Py3 supposed to be supported?

Tests?

Would be great to have a simple test suite.

tags on github

PyPI is nice, but I prefer real sources from git, not the preprocessed ones.

Should frozendict be ordered as of Python 3.7?

Hello! I have a question, and I'm wondering if this is just something that can be clarified prominently in documentation, or if it's something that can be changed in the implementation. As of Python 3.7, dict is ordered by insertion order, and OrderedDict is now redundant. This can be seen in the "What's New" page, and was decreed by Guido: https://docs.python.org/3/whatsnew/3.7.html

Should frozendict also be made to remember the insertion order officially, to match the newer behaviour of dict, if and only if you're using Python 3.7?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.