From 5208c0d28a98113dbc6281c9e8cd14e743218bb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Tue, 13 Aug 2024 15:57:17 +0200 Subject: [PATCH] [util] extend CustomNone with an __index__ method (#6009) - Make it compatible with functions expecting integer arguments - Simplify and reuse some method definitions --- gallery_dl/util.py | 21 ++++++--------------- test/test_util.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index f1bd53cc..9596c16a 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -520,14 +520,9 @@ class CustomNone(): """None-style type that supports more operations than regular None""" __slots__ = () - def __getattribute__(self, _): - return self - - def __getitem__(self, _): - return self - - def __iter__(self): - return self + __getattribute__ = identity + __getitem__ = identity + __iter__ = identity def __call__(self, *args, **kwargs): return self @@ -536,10 +531,6 @@ class CustomNone(): def __next__(): raise StopIteration - @staticmethod - def __bool__(): - return False - def __eq__(self, other): return self is other @@ -550,6 +541,7 @@ class CustomNone(): __le__ = true __gt__ = false __ge__ = false + __bool__ = false __add__ = identity __sub__ = identity @@ -588,9 +580,8 @@ class CustomNone(): def __len__(): return 0 - @staticmethod - def __hash__(): - return 0 + __hash__ = __len__ + __index__ = __len__ @staticmethod def __format__(_): diff --git a/test/test_util.py b/test/test_util.py index 73a8928a..efbb0a19 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -12,6 +12,7 @@ import sys import unittest import io +import time import random import string import datetime @@ -741,6 +742,9 @@ def hash(value): self.assertFalse(obj) self.assertEqual(len(obj), 0) + self.assertEqual(int(obj), 0) + self.assertEqual(hash(obj), 0) + self.assertEqual(str(obj), str(None)) self.assertEqual(repr(obj), repr(None)) self.assertEqual(format(obj), str(None)) @@ -751,6 +755,7 @@ def hash(value): self.assertIs(obj(), obj) self.assertIs(obj(1, "a"), obj) self.assertIs(obj(foo="bar"), obj) + self.assertIs(iter(obj), obj) self.assertEqual(util.json_dumps(obj), "null") self.assertLess(obj, "foo") @@ -797,6 +802,12 @@ def hash(value): mapping = {} mapping[obj] = 123 self.assertIn(obj, mapping) + self.assertEqual(mapping[obj], 123) + + array = [1, 2, 3] + self.assertEqual(array[obj], 1) + + self.assertTrue(time.localtime(obj)) i = 0 for _ in obj: