Home > OS >  How to pass a const queue to a function?
How to pass a const queue to a function?

Time:12-02

I am a C guy. I am aware python denounces the const keyword in favour of "we are grownups, we trust each other".

Now I need to inform some python threads of some messages and decided to use a queue. The messages are strings of length up to 1024 characters. I find it absurd that those threads can change those messages for the calling thread or even for themselves.

How can that be prevented? Or is it already?

CodePudding user response:

TLDR: Convert your data to one of the immutable types, or create a frozen type. Primitive data such as numbers and strings are always immutable.


Python offers several ways of constructing immutable or quasi-immutable values.

  • Primitives like numbers, strings and similar are always immutable.
  • Containers offer some immutable types, such as tuple or frozenset as immutable sequence or set.
  • Custom types can be defined as immutable, for example using NamedTuple or frozen dataclass.

Ideally, data intended to be shared should directly be constructed using immutable types. When this is not possible, convert the data from mutable to immutable type before sharing.

>>> # strings are always immutable
>>> data = "Hello World!"
>>> data[:5] = "Howdy"
....
TypeError: 'str' object does not support item assignment
>>> # sequence are mutable or immutable
>>> data = ["Hello", "World"]
>>> idata = tuple(data)  # create immutable from mutable sequence
>>> data[0] = "Howdy"
>>> idata[0] = "Howdy"
...
TypeError: 'tuple' object does not support item assignment
>>> data, idata
(['Howdy', 'World'], ('Hello', 'World'))
  • Related