Issue
I need to make dictionary available as context var. I was trying to use @property setter, but don't understand how to correctly set key/value in this case.
I have websockets server and i need to make dictionary variable be unique for each client. Of course i can use get and set methods of contextvar each time i need to change dict i.e.
d = dict_var.get()
d['key']='val'
dict_var.set(d)
but it looks like a not good way
So, i'm trying to find proper way on how to use contextvar with dict, or how to make dict unique for asyncio task context (websockets server is async)
Solution
The way I see it, contextvars should be a last resort to most problems. There are many cases where contextvars makes perfect sense, but it is not the tool for every job.
What is wrong with having this dictionary and passing it around? If you don't want to pass it around in your code then you could store it in a central place (in another dictionary, with the websocket as the key).
You really only have two options here. Either continue calling .get()
, modifying the dictionary and calling .set()
- or pass around the dictionary in your code directly.
Answered By - Bluenix
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.