1

I would like to use a dictionary that only allows a single write of any specific key.

Is there a (fool-proof) python subclass for a dictionary that will raise an exception when trying to overwrite a key?

EDIT: Alternatively, is there a simple way to throw an exception that is fool-proof for any type of dictionary update?

Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74
  • 1
    You could subclass dict and overwrite `__setitem__`, and also `__delitem__`, `clear`, etc. – tobias_k Jan 12 '21 at 11:14
  • 1
    Refer to this link -> https://stackoverflow.com/questions/11014262/how-to-create-an-immutable-dictionary-in-python – mzebin Jan 12 '21 at 11:14

1 Answers1

0

I don't know a built-in way of achieving this, But one solution might be to just add a Boolean value to the each value in the dict. When initializing the dict, you set this Boolean to True and after the first overwrite you change it to False. Everytime you try to change some value, you first check this boolean. True means it's okay to change it, False means it's not.

Gal Birka
  • 581
  • 6
  • 16