Created
July 26, 2025 17:23
-
-
Save moreati/dae4973f52237afc378f71ca2f9b3f81 to your computer and use it in GitHub Desktop.
A minimal integer ID type that intentionally doesn't support mathematical operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # A minimalist integer ID type that intentionally doesn't support mathematical | |
| # operations. Subclass it to make e.g. UserID type, FileDescriptor type | |
| class ID(object): | |
| __slots__ = ('_v',) | |
| def __init__(self, v): | |
| if not isinstance(v, int): | |
| raise TypeError('int required, got: %s"' % type(v)) | |
| if v < 0: | |
| raise ValueError('cannot be negative', v) | |
| super(ID, self).__setattr__('_v', v) | |
| def __setattr__(self, name, v): raise AttributeError('Immutable') | |
| def __eq__(self, x): return isinstance(x, type(self)) and self._v == x._v | |
| def __hash__(self): return hash((self._v,)) | |
| def __int__(self): return self._v | |
| def __str__(self): return str(self._v) | |
| def __repr__(self): return '%s(%d)' % (type(self).__name__, self._v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment