Ian
Ian

Reputation: 6144

Python version of JavaScript ES6 Symbols

Is there a Python version of JavaScript's Symbol type? If not, what's the Pythonic way to declare a guaranteed-unique constant or property?

For example, in JavaScript, one could do:

const ALL_VALUES = Symbol()
const EVERY_OTHER_VALUE = Symbol()

function do_something_to_values(
    list_of_values, 
    values_to_affect
) {
    ...
}

And then one could call do_something_to_values(my_list, EVERY_OTHER_VALUE) and the function would check for equality to the EVERY_OTHER_VALUE constant.

How would one do this in Python?

Upvotes: 4

Views: 455

Answers (2)

David K. Hess
David K. Hess

Reputation: 17246

There was also a proposal to add a "Sentinel" class to the Python standard library:

https://peps.python.org/pep-0661/

That points you to a GitHub repo containing a reference implementation:

https://github.com/taleinat/python-stdlib-sentinels

It has a license allowing incorporation in any project.

Upvotes: 0

Luke Miles
Luke Miles

Reputation: 1170

The keyword you’re looking for is sentinel. There’s been lots of discussion of this over the years. This is a good fairly recent solution

https://www.revsys.com/tidbits/sentinel-values-python/

Upvotes: 2

Related Questions