[Tutor] use of dict() function

Mats Wichmann mats at wichmann.us
Wed Jun 12 14:41:04 EDT 2024


On 6/12/24 11:58, Alex Kleider wrote:
> On the contrary, I have _not_ figured it out!
> My goal is to have a way of creating an object (a class instance,) in
> this case a dict, without there being any chance of the original dict
> (the parameter of the init call) being modified.

You need to get pretty involved to accomplish that.  ChainMap is a cheap 
approximation, which presumably is believed to be "good enough" in many 
cases.

=== docs:
A ChainMap groups multiple dicts or other mappings together to create a 
single, updateable view. If no maps are specified, a single empty 
dictionary is provided so that a new chain always has at least one mapping.
...
Lookups search the underlying mappings successively until a key is 
found. In contrast, writes, updates, and deletions only operate on the 
first mapping.
===

So the second (and additional) dicts in the chain don't get modified by 
normal dictionary operations, as long as they're done on the view 
(chain).  But the non-primary can still be modified directly. And 
indirectly as well.

Some of this has actually been requested many times as an "immutable 
dict". Because the term has been used for other data types, it was once 
formally proposed as FrozenDict, though the proposal was not accepted. 
You can find various attempts at implementation on the internet (I've 
been here too, have a need for a backing dict to not get accidentally 
modified when using an "override" object). Actually there have been two 
PEPs - one for a native type, one for an implementation in the 
collections module.  If you want to have your head spin a bit, it's 
these two:

https://peps.python.org/pep-0416/
https://peps.python.org/pep-0603/

The thing you have to think about is if your "d0" contains values that 
are mutable objects (list, an inner dict, etc.), and you fetch one 
through "d1", now you have a handle to that object, and while you can't 
modify "d0" through "d1" itself, if you modify the object you fetched, 
then "d0" will still look updated.

> (... and also to have the additional feature of being able to "call"
> the instance and get the dict formatted as specified by the string
> parameter.)

Why would you use a call method? typically a str or repr magic method 
would provide this functionality, that's what they exist for.



More information about the Tutor mailing list