(original) (raw)
from weakref import WeakKeyDictionary class Default(object): """A descriptor that allows default values. Pretty useless but shows the bug in question.""" def __init__(self, default): self.default = default self.data = WeakKeyDictionary() def __get__(self, instance, owner): return self.data.get(instance, self.default) def __set__(self, instance, value): self.data[instance] = value class Something(object): def_a = Default('a') def_none = Default(None) @property def a_prop(self): return None if __name__ == '__main__': thing = Something() print "# normal access" print "thing.def_a :", thing.def_a print "thing.def_none :", thing.def_none print "thing.a_prop :", thing.a_prop print print "# getattr access" print "getattr(thing, 'def_a') :", getattr(thing, 'def_a') print "getattr(thing, 'def_none') :", getattr(thing, 'def_none') print "getattr(thing, 'def_none', 'val_if_none') :", getattr(thing, 'def_none', 'val_if_none') print "getattr(thing, 'a_prop') :", getattr(thing, 'a_prop') print "getattr(thing, 'a_prop', 'val_if_none') :", getattr(thing, 'a_prop', 'val_if_none') print a_dict = {'things_def_none': thing.def_none} print "# a_dict = {'things_def_none': thing.def_none}" print "a_dict['things_def_none'] :", a_dict['things_def_none'] print "a_dict.get('things_def_none', 'val_if_none'):", a_dict.get('things_def_none', 'val_if_none')