The practical use of a tuple as a singleton

In the documentation on data models, it mentions the possibility of using one element of a tuple as a singleton, because of its immutability.

tuples

A tuple of a single element ("singleton") can be formed by attaching a comma to an expression ...

As far as I understand in Python, singleton functions similarly to a constant. This is a fixed value that supports the same memory address so you can verify equality or identity. For example, None , True and False are all built-in singletones.

However, using a tuple defined in this way seems impractical for inconvenient syntax, given this kind of use:

 HELLO_WORLD = ("Hello world",) print HELLO_WORLD > ('Hello world',) print HELLO_WORLD[0] > Hello world 

Not to mention that it only works as a single if you don't want to index it.

 HELLO_WORLD[0] = "Goodbye world" Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> HELLO_WORLD[0] = "Goodbye world" TypeError: 'str' object does not support item assignment 

So you could easily do this:

 HELLO_WORLD = "Goodbye world" print HELLO_WORLD > Goodbye world 

Given these limitations, is there any point for this singleton implementation? The only advantage I see is simple creation. Other approaches that I saw were more complex approaches (using classes, etc.), but is there any other use for this that I don't think about?

+4
source share
1 answer

I don’t think this is useful for single player games at all, it doesn’t add anything: a tuple can still be overwritten with a new singleton tuple. Anyway, in your example, your value is a string that is already immutable in itself.

But I think that the documentation line you are referring to ("Single element tuple (" singleton ")) does not refer to the singleton pattern at all, but rather to the mathematical use of the word, see Wikipedia on singleton (math)

This term is also used for a 1-tuple (single-element sequence).

+7
source

All Articles