I want to represent the value of nil
, a value specific to my application, and distinguish it from the None
built in to Python. What is the most elegant way to do this? Note that nil
is a unique constant value.
Asked
Active
Viewed 444 times
1

user3793111
- 11
- 1
1 Answers
6
Use a sentinel object:
nil = object()
Now you can test for is nil
or is not nil
just as you can test for None
.
Any code that uses this does, of course, have to import it from the module that defines it; it is not a built-in the way None
is built-in.

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343
-
If I make another constant in the same way, will that be distinct from `nil`? And is the best practice to simply leave nil in global scope in a file, if I want to expose it as much as a regular class (since I essentially want this to represent a class with only one object). – user3793111 Jul 01 '14 at 08:44
-
If you test with `is` the other value will be different. – Matthias Jul 01 '14 at 08:51
-
@Matthias For `object` instances, even `==` will consider them distinct. It's just not idiomatic to compare such "singletons" with `==` (also applies to `None`, `Ellipsis` and `NotImplemented`). – Jul 01 '14 at 08:54
-
@delnan: Still learning after all those years ... – Matthias Jul 01 '14 at 09:13
-
@user3793111: yes, another constant will be entirely distinct. – Martijn Pieters Jul 01 '14 at 09:35