Skip to content

Instantly share code, notes, and snippets.

@arccoder
Last active April 12, 2023 23:52
Show Gist options
  • Save arccoder/27609d200612babf11fb09f713a15c33 to your computer and use it in GitHub Desktop.
Save arccoder/27609d200612babf11fb09f713a15c33 to your computer and use it in GitHub Desktop.
Python: Read only dictionary
class ReadOnlyDict(dict):
def __setitem__(self, key, value):
raise RuntimeError("Modification not supported")
rw_dict = {'key': 'original'}
print('Dict: ' + str(rw_dict))
ro_dict = ReadOnlyDict(rw_dict)
print('ReadOnlyDict: ' + str(ro_dict))
rw_dict['key'] = 'modified'
print('Dict: ' + str(rw_dict))
ro_dict['key'] = 'modified' # RuntimeError: Modification not supported
print('ReadOnlyDict: ' + str(ro_dict))
import copy
def method(in_dict):
print('Method: ' + str(in_dict))
in_dict['key'] = 'modified'
print('Method: ' + str(in_dict))
rw_dict = {'key': 'original'}
print('Original: ' + str(rw_dict))
method(copy.deepcopy(rw_dict))
print('Original: ' + str(rw_dict))
from types import MappingProxyType
rw_dict = {'key': 'original'}
ro_dict = MappingProxyType(rw_dict)
# ro_dict['key'] = 'modified' # TypeError: 'mappingproxy' object does not support item assignment
rw_dict['key'] = 'modified'
print(ro_dict) # Output: {'key': 'modified'}
import threading
import time
from types import MappingProxyType
def thread_function(name, in_dict):
print("Thread %s: starting" % name)
print("Thread %s: %s" % (name, str(in_dict)))
print("Thread %s: wait for 5 seconds" % name)
time.sleep(5)
print("Thread %s: %s" % (name, str(in_dict)))
print("Thread %s: finishing" % name)
# in_dict['key'] = 'modified' # TypeError: 'mappingproxy' object does not support item assignment
if __name__ == "__main__":
rw_dict = {'key': 'original'}
ro_dict = MappingProxyType(rw_dict)
print("Main : " + str(ro_dict))
print("Main : before creating thread")
x = threading.Thread(target=thread_function, args=(1, ro_dict,))
print("Main : before running thread")
x.start()
print("Main : wait for 2 seconds")
time.sleep(2)
rw_dict['key'] = 'modified' # Modify value
print("Main : " + str(ro_dict))
print("Main : wait for the thread to finish")
# x.join()
print("Main : all done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment