1 #!/usr/bin/env python 2 3 """ 4 Identity-related functions. 5 6 Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from native import _isinstance, _issubclass 23 24 def callable(obj): 25 26 "Return whether 'obj' is callable." 27 28 # NOTE: Classes and functions are callable, modules are not callable, 29 # NOTE: only instances with __call__ methods should be callable. 30 31 pass 32 33 def help(*args): 34 35 # NOTE: This should show any docstring, but it is currently unsupported. 36 37 pass 38 39 def id(obj): 40 41 # NOTE: This should show an object's address, but it is currently 42 # NOTE: unsupported. 43 44 pass 45 46 def isclass(obj): 47 48 "Return whether 'obj' is a class." 49 50 return obj.__class__ is type 51 52 def isinstance(obj, cls_or_tuple): 53 54 """ 55 Return whether 'obj' is an instance of 'cls_or_tuple', where the latter is 56 either a class or a sequence of classes. 57 """ 58 59 if _isinstance(cls_or_tuple, tuple): 60 for cls in cls_or_tuple: 61 if obj.__class__ is cls or isclass(cls) and _isinstance(obj, cls): 62 return True 63 return False 64 else: 65 return obj.__class__ is cls_or_tuple or isclass(cls_or_tuple) and _isinstance(obj, cls_or_tuple) 66 67 def issubclass(obj, cls_or_tuple): 68 69 """ 70 Return whether 'obj' is a class that is a subclass of 'cls_or_tuple', where 71 the latter is either a class or a sequence of classes. If 'obj' is the same 72 as the given class or classes, True is also returned. 73 """ 74 75 if not isclass(obj): 76 return False 77 elif _isinstance(cls_or_tuple, tuple): 78 for cls in cls_or_tuple: 79 if obj is cls or isclass(cls) and _issubclass(obj, cls): 80 return True 81 return False 82 else: 83 return obj is cls_or_tuple or isclass(cls_or_tuple) and _issubclass(obj, cls_or_tuple) 84 85 def repr(obj): 86 87 "Return a program representation for 'obj'." 88 89 # Classes do not provide __repr__ directly. 90 91 if isclass(obj): 92 return obj.__name__ 93 94 # Class attributes of instances provide __repr__. 95 96 else: 97 return obj.__repr__() 98 99 # vim: tabstop=4 expandtab shiftwidth=4