1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 """
18 This modules provides the MinimalMatch class. Subclasses from this
19 class have the special property that attribute names can be
20 abbreviated:
21
22 >>> class MyClass(MinimalMatch):
23 ... user = 'root'
24 ... start = 'yesterday'
25 ... stop = 'tomorrow'
26 ...
27 >>> my_instance = MyClass()
28
29 For instance the following command will set the 'user' attribute:
30
31 >>> my_instance.u = 'nobody'
32 >>> print my_instance.user
33 nobody
34
35 But of course you can always use the full attribute name:
36
37 >>> my_instance.user = 'root'
38 >>> print my_instance.us
39 root
40
41 Never type more than the full attribute name:
42
43 >>> print my_instance.users
44 Traceback (most recent call last):
45 ...
46 AttributeError: MyClass instance has no attribute 'users'
47
48 Abbreviations should not be ambiguous:
49
50 >>> my_instance.st = 'now'
51 Traceback (most recent call last):
52 ...
53 AttributeError: MyClass instance attribute 'st' is ambiguous
54
55 And setting instance attributes that are not class attributes is not
56 possible:
57
58 >>> my_instance.group = 'nobody'
59 Traceback (most recent call last):
60 ...
61 AttributeError: MyClass instance has no attribute 'group'
62
63 >>> print my_instance.stop
64 tomorrow
65
66 Getting and setting private attributes should just work:
67
68 >>> my_instance._private = ('do', 'not', 'touch')
69 >>> print my_instance._private
70 ('do', 'not', 'touch')
71
72 And accesing non-existent private attributes should fail (and not land
73 us in an infinite loop):
74
75 >>> print my_instance._does_not_exist
76 Traceback (most recent call last):
77 ...
78 AttributeError: MyClass instance has no attribute '_does_not_exist'
79
80 """
81
83 """ Allow class attribute names to be abbreviated. """
84
86
87 if name.startswith('_'):
88 return name
89
90 match_attr = None
91 if name in self.__dict__:
92 match_attr = name
93 else:
94 for dict in self.__dict__, self.__class__.__dict__:
95 for attr in dict:
96 if attr.startswith(name):
97 if match_attr and attr != match_attr:
98 msg = "%s instance attribute '%s' is ambiguous" \
99 % (self.__class__.__name__, name)
100 raise AttributeError, msg
101 else:
102 match_attr = attr
103
104 if not match_attr:
105 msg = "%s instance has no attribute '%s'" \
106 % (self.__class__.__name__, name)
107 raise AttributeError, msg
108
109 return match_attr
110
112 attr = self._findattr(name)
113 if hasattr(self, attr):
114 return getattr(self, attr)
115
116 msg = "%s instance has no attribute '%s'" \
117 % (self.__class__.__name__, name)
118 raise AttributeError, msg
119
123
124
125
126 if __name__ == '__main__':
127 import doctest, sys
128 results = doctest.testmod(sys.modules[__name__])
129 sys.exit(results[0])
130