slezica / python-frozendict

A simple immutable mapping for python
MIT License
111 stars 22 forks source link

Nested dicts are not supported #35

Open raul-openai opened 3 years ago

raul-openai commented 3 years ago

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.

raul-openai commented 3 years ago

I guess we can just deepcopy the dict.

frozendict(copy.deepcopy(orig_top))
raul-openai commented 3 years ago

It would still probably be worth providing that functionality in the constructor (eg: bool flag), since this can be an error prone default.