Skip to content

Instantly share code, notes, and snippets.

@stkrp
Last active June 15, 2020 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stkrp/8247f6b986405a2ca094ea9026fde639 to your computer and use it in GitHub Desktop.
Save stkrp/8247f6b986405a2ca094ea9026fde639 to your computer and use it in GitHub Desktop.
Least and greatest objects in python
class _Singleton(type):
_instances = {}
def __call__(cls, *pargs, **kwargs):
mcls = cls.__class__
if cls not in mcls._instances:
mcls._instances[cls] = super().__call__(*pargs, **kwargs)
return mcls._instances[cls]
class Least(metaclass=_Singleton):
"""
The type of objects that are smaller than the others. It is used to sort
the elements of different types, replacing the incomparable types.
>>> sorted(
... [1, 2, 3, None, 3, 2, 1, 4, 5, None, 6],
... key=lambda num: num if isinstance(num, (int, float)) else Least()
... )
[None, None, 1, 1, 2, 2, 3, 3, 4, 5, 6]
"""
def __lt__(self, other):
return True
def __gt__(self, other):
return not self.__lt__(other)
class Greatest(metaclass=_Singleton):
"""
The type of objects that are greater than the others. It is used to sort
the elements of different types, replacing the incomparable types.
>>> sorted(
... [1, 2, 3, None, 3, 2, 1, 4, 5, None, 6],
... key=lambda num: num if isinstance(num, (int, float)) else Greatest()
... )
[1, 1, 2, 2, 3, 3, 4, 5, 6, None, None]
"""
def __gt__(self, other):
return True
def __lt__(self, other):
return not self.__gt__(other)
@stkrp
Copy link
Author

stkrp commented Jun 15, 2020

Можно переделать в Singleton.

В любом случае нужно сделать, чтобы все экземпляры были равны между собой.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment