Created
July 20, 2014 04:16
-
-
Save dutc/88df5ddcc223a4bc983f to your computer and use it in GitHub Desktop.
custom type system using __instancecheck__
This file contains 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
class FoobarMeta(type): | |
def __instancecheck__(self, obj): | |
return hasattr(obj, 'foo') and hasattr(obj, 'bar') | |
class Foobar(metaclass=FoobarMeta): | |
pass | |
class A: | |
def foo(self): | |
pass | |
class B: | |
def foo(self): | |
pass | |
def bar(self): | |
pass | |
class C: | |
def bar(self): | |
pass | |
if __name__ == '__main__': | |
a, b, c = A(), B(), C() | |
assert not isinstance(a, Foobar) | |
assert isinstance(b, Foobar) | |
assert isinstance(c, Foobar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment