Tagging a Card With a Symbol

The Harbour card has a title, a price, and a locked ID. Before a customer sees it, the proof desk wants to tag it with where it was checked. That tag is shop bookkeeping, and it mustn’t collide with any key the card already uses.

A string key such as "source" is risky because a customer’s upload details could arrive under the same name and overwrite the tag. A Pythonista might use a prefixed name such as "_desk_source", but a prefix only lowers the odds because any other code can still type the same string. In this lesson, you’ll give the tag a key that no other code can spell, starting from the unique key Python already gives you.

Make a Key Nothing Else Can Equal

In Python, when you need a marker that can’t clash with any real value, you create a sentinel with object(). Each call returns a new object, so two sentinels are never the same, and a dictionary can use one as a key:

Language: Python
>>> SOURCE = object()
>>> other_source = object()
>>> SOURCE is other_source
False
>>> tags = {SOURCE: "proof desk"}
>>> tags[SOURCE]
'proof desk'

Every object() has its own identity, so no other code can look that entry up by accident, though anything that loops over tags can still find it. JavaScript has a value built for the same job.

Calling Symbol() creates a symbol, a primitive value that’s unique the moment it’s made. You call it as a plain function, without new, because Symbol isn’t a constructor, and new Symbol() throws a TypeError. The text you pass in is a description, a label for humans reading the output.

In the JavaScript port, const declares a name that can’t be reassigned, console.log() prints a value, and === compares two values strictly. Make two symbols with the same description and compare them:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.