Lichen

lib/__builtins__/attribute.py

1022:582d834d392d
14 months ago Paul Boddie Merged changes from the value-replacement branch. value-replacement-for-wrapper
     1 #!/usr/bin/env python     2      3 """     4 Attribute-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 __builtins__.types import check_string    23 from native import object_getattr    24     25 _default=object() # a unique placeholder for a missing value    26     27 def getattr(obj, name, default=_default):    28     29     """    30     Return for 'obj' the attribute having the given 'name', returning the given    31     'default' if the attribute is not defined for 'obj', raising an exception if    32     'default' is not indicated and the attribute is not defined.    33     """    34     35     check_string(name)    36     37     # Attempt to obtain the attribute. If the name is not recognised as an    38     # attribute name, the default will be returned. Otherwise, an access    39     # operation will be attempted.    40     41     try:    42         result = object_getattr(obj, name, default)    43     44     # Handle exceptions when the access operation fails.    45     46     except TypeError:    47         result = _default    48     49     # Check the result and, if it is the placeholder value, raise an exception.    50     51     if result is _default:    52         raise AttributeError(name)    53     54     # Otherwise, return the obtained value or supplied default.    55     56     else:    57         return result    58     59 def hasattr(obj, name):    60     61     "Return whether 'obj' has an attribute called 'name'."    62     63     try:    64         getattr(obj, name)    65     except AttributeError:    66         return False    67     else:    68         return True    69     70 # NOTE: setattr would probably only be supported on instances due to deductions    71 # NOTE: applying to static objects being undermined by dynamic modifications.    72     73 def setattr(obj, name, value):    74     raise NotImplementedError, "setattr"    75     76 # vim: tabstop=4 expandtab shiftwidth=4