2

Javascript symbols provide simple unique identifiers:

> const foo1 = Symbol('foo');
> foo1
Symbol(foo)
> const foo2 = Symbol('foo');
> foo1 === foo2
false
> let m = new Map();
> m.set(foo1, "bar");
> m.set(foo2, "rosco");
> m.get(foo1)
'bar'
> m.get(foo2)
'rosco'

This is useful for e.g. having unique return values from functions with special meanings when you can't use Exceptions.

I know in python you can use object() or a nonce but neither of those render nice when you print them.

Is there anything like javascript's Symbol available in python?

Luke Miles
  • 941
  • 9
  • 19

1 Answers1

5

Edited:

This class mimics the javascript counterpart.

Unlike js, Python accepts an object's instance as dictionary key; this code just add a proper representation when printing the symbol.

class Symbol:
    def __init__(self, name=''):
        self.name = f"Symbol({name})"
    def __repr__(self):
        return self.name

# === test ===

foo1 = Symbol('foo')
print(foo1)
foo2 = Symbol('foo')
print(foo1 == foo2)
m = {}
m[foo1] = "bar"
m[foo2] = "rosco"

print(m[foo1])
print(m[foo2])

> Symbol(foo)
> False
> bar
> rosco
ej1
  • 66
  • 4
  • When you answer on stackoverflow, you generally need to give an explanation. Please explain what you have tried here. Thanks! – 10 Rep May 11 '20 at 17:14