You can implement wild-card matching using a special object that is always compared to any other object. For instance,
#!/usr/bin/env python class Any: def __eq__(self, other): return True def __repr__(self): return 'Any' ANY = Any()
Output
Any 1 True 2 True a True b True (2, 3, 4) True None True [(0, 1), (4, 1)]
Here is the best version with fancier Any class thanks to Antti Haapala . It prints the same result as the code above.
#!/usr/bin/env python class AnyBase(type): def __eq__(self, other): return True def __repr__(self): return 'Any' @classmethod def __subclasscheck__(cls, other): return True @classmethod def __instancecheck__(cls, other): return True class Any(object): __metaclass__ = AnyBase def __init__(self): raise NotImplementedError("How'd you instantiate Any?")
To use the first version, we really need to create an instance of the class, but the Any class in the second version is intended for direct use. In addition, the second version shows how to handle isinstance and subclass ; depending on the context, you can limit these tests.
source share