0

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)

Digital God
  • 471
  • 1
  • 5
  • 17

1 Answers1

0

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.

Bluenix
  • 409
  • 4
  • 11
  • I missed a very obvious option - make dict of dicts, where each key represents websocket connection. Every time I delve into some complex technology, I miss the obvious options. – Digital God Jan 29 '22 at 10:03
  • 1
    the problem with creating a key for each connection is that this won't delete the key, and yo. will leak data for each connection. If you add a mechanism to do that, it is ok. – jsbueno Feb 17 '22 at 15:27