Mercurial > hg > pyloader
comparison pyloader/cast.py @ 2:6cb7696edc4d
add some more stuff for string loady type things and rearrange structure
| author | Jeff Hammel <jhammel@mozilla.com> |
|---|---|
| date | Tue, 10 May 2011 09:28:40 -0700 |
| parents | |
| children | 5ce55f6c8964 |
comparison
equal
deleted
inserted
replaced
| 1:47d9472e7754 | 2:6cb7696edc4d |
|---|---|
| 1 class StringCastException(Exception): | |
| 2 """raised on unsucessful cast""" | |
| 3 | |
| 4 class StringCaster(object): | |
| 5 """cast strings to other things""" | |
| 6 # as yet unused | |
| 7 | |
| 8 def __init__(self, *casts): | |
| 9 self.casts = casts | |
| 10 | |
| 11 def __call__(self, string): | |
| 12 for cast in self.casts: | |
| 13 try: | |
| 14 return cast(string) | |
| 15 except: | |
| 16 continue | |
| 17 return string | |
| 18 | |
| 19 ### casters | |
| 20 | |
| 21 def str2bool(string): | |
| 22 mapping = {'true': True, | |
| 23 'True': True, | |
| 24 'false': False, | |
| 25 'False': False} | |
| 26 return mapping[string] | |
| 27 | |
| 28 def str2list(string, separator=None): | |
| 29 string = string.rstrip(separator) | |
| 30 return [i.strip() for i in string.split(separator)] | |
| 31 | |
| 32 def str2args(string, separator=None): | |
| 33 args = str2list(string, separator) | |
| 34 _args = [] | |
| 35 kw = {} | |
| 36 for arg in args: | |
| 37 if '=' in arg: | |
| 38 pass | |
| 39 else: | |
| 40 _args.append(arg) | |
| 41 return _args, kw | |
| 42 | |
| 43 # convenience functions | |
| 44 casts = [int, float, str2bool, str2list, str2args] | |
| 45 cast = StringCaster(*casts) | |
| 46 | |
| 47 if __name__ == '__main__': | |
| 48 import sys | |
| 49 for arg in sys.argv[1:]: | |
| 50 print cast(arg) |
