SuperBiasedMan
SuperBiasedMan

Reputation: 9969

Practical use of tuple as a singleton

In the documentation on data models it mentions the possibility to use a single item tuple as a singleton, due to it's immutability.

Tuples

A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression...

As far as I understand it in Python, a singleton functions similarly to a constant. It is a fixed value that maintains the same memory address so that you can test either equality or identity. For instance, None, True and False are all builtin singletons.

However using a tuple defined this way seems impractical for awkward syntax, considering this kind of usage:

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

Not to mention, it only functions as a singleton if you remember 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

Meaning that you could easily do this:

HELLO_WORLD = "Goodbye world"
print HELLO_WORLD
> Goodbye world

Given these limitations, is there any point to this singleton implementation? The only advantage I see is that it's simple to create. Other approaches I've seen have been more complicated approaches (using classes etc.) but is there some other use for this I'm not thinking of?

Upvotes: 6

Views: 1995

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31260

I don't think this is useful for implementing singletons at all, it doesn't add anything: the tuple can still be overwritten by a new single-element tuple. Anyway, in your example your value is a string, which is already immutable itself.

But I think the line of documentation you refer to ("A tuple of one item (a ‘singleton’)"), doesn't refer to the singleton pattern at all, but rather to the mathematical usage of the word, see Wikipedia on Singleton (mathematics)

The term is also used for a 1-tuple (a sequence with one element).

Upvotes: 9

Related Questions