niltype: Singleton for Missing Values
A small Python library that provides a singleton `Nil` object. This object is designed to represent missing or unset values in scenarios where `None` is a valid and meaningful data value, thus avoiding ambiguity. Currently at version 1.0.2, it's a stable, single-purpose library with infrequent updates.
Common errors
-
AttributeError: 'NilType' object has no attribute 'some_property'
cause Attempting to access attributes or methods on a variable that holds `Nil` without first checking for its presence.fixAlways check `if my_var is not Nil:` before attempting to access properties or methods on `my_var`, as `Nil` has no user-defined attributes. -
TypeError: can't concat NilType to str
cause Passing `Nil` directly to functions or operations that expect a specific data type (e.g., string concatenation, arithmetic operations, database queries) and do not explicitly handle `Nil`.fixImplement explicit checks for `Nil` and handle it appropriately (e.g., return early, provide a default value, raise a more specific exception) before passing the variable to type-sensitive operations. For example: `my_str = 'Default' if my_var is Nil else str(my_var)`.
Warnings
- gotcha The `Nil` object evaluates to `False` in a boolean context, similar to `None`, empty collections, or zero. However, `Nil` is not `None` (`Nil != None`).
- gotcha `Nil` is a true singleton, meaning there is only one instance of it throughout your application's lifetime. Any variable assigned `Nil` will reference this single instance.
Install
-
pip install niltype
Imports
- Nil
from niltype import Nil
Quickstart
from niltype import Nil
def get_user_setting(user_id: int, setting_name: str):
"""Simulates fetching a user setting where Nil means 'not found'."""
if user_id == 1:
if setting_name == "theme":
return "dark"
elif setting_name == "timeout":
return None # None is a valid timeout (e.g., no timeout)
return Nil # Setting does not exist for this user
# Example usage:
setting = get_user_setting(1, "theme")
print(f"Theme setting: {setting} (is Nil: {setting is Nil})")
setting = get_user_setting(1, "timeout")
print(f"Timeout setting: {setting} (is Nil: {setting is Nil})")
setting = get_user_setting(2, "language")
print(f"Language setting: {setting} (is Nil: {setting is Nil})")
if setting is Nil:
print("\nSetting 'language' for user 2 is missing.")
elif setting is None:
print("\nSetting 'timeout' is explicitly set to None (no timeout).")
else:
print(f"\nSetting is {setting}.")