paul@6 | 1 | #!/usr/bin/env python |
paul@6 | 2 | |
paul@6 | 3 | """ |
paul@6 | 4 | Attribute-related functions. |
paul@6 | 5 | |
paul@228 | 6 | Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> |
paul@6 | 7 | |
paul@6 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@6 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@6 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@6 | 11 | version. |
paul@6 | 12 | |
paul@6 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@6 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@6 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@6 | 16 | details. |
paul@6 | 17 | |
paul@6 | 18 | You should have received a copy of the GNU General Public License along with |
paul@6 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@6 | 20 | """ |
paul@6 | 21 | |
paul@228 | 22 | from native import _object_getattr |
paul@228 | 23 | |
paul@228 | 24 | _default=object() # a unique placeholder for a missing value |
paul@228 | 25 | |
paul@228 | 26 | def _getattr(obj, name, default=_default): |
paul@6 | 27 | |
paul@228 | 28 | """ |
paul@228 | 29 | Return for 'obj' the attribute having the given 'name', returning the given |
paul@228 | 30 | 'default' if the attribute is not defined for 'obj'. |
paul@228 | 31 | """ |
paul@6 | 32 | |
paul@228 | 33 | return _object_getattr(obj, name, default) |
paul@228 | 34 | |
paul@228 | 35 | def getattr(obj, name, default=_default): |
paul@6 | 36 | |
paul@228 | 37 | """ |
paul@228 | 38 | Return for 'obj' the attribute having the given 'name', returning the given |
paul@228 | 39 | 'default' if the attribute is not defined for 'obj', raising an exception if |
paul@228 | 40 | 'default' is not indicated and the attribute is not defined. |
paul@228 | 41 | """ |
paul@228 | 42 | |
paul@228 | 43 | result = _getattr(obj, name, default) |
paul@228 | 44 | |
paul@228 | 45 | if result is _default: |
paul@228 | 46 | if default is _default: |
paul@228 | 47 | raise AttributeError(name) |
paul@6 | 48 | else: |
paul@228 | 49 | return default |
paul@228 | 50 | else: |
paul@228 | 51 | return result |
paul@228 | 52 | |
paul@228 | 53 | def hasattr(obj, name): |
paul@6 | 54 | |
paul@228 | 55 | "Return whether 'obj' has an attribute called 'name'." |
paul@228 | 56 | |
paul@228 | 57 | result = _getattr(obj, name) |
paul@228 | 58 | return result is not _default |
paul@228 | 59 | |
paul@6 | 60 | def setattr(obj, name, value): pass |
paul@6 | 61 | |
paul@6 | 62 | # vim: tabstop=4 expandtab shiftwidth=4 |