Mercurial > fife-parpg
comparison engine/extensions/pychan/attrs.py @ 0:4a0efb7baf70
* Datasets becomes the new trunk and retires after that :-)
author | mvbarracuda@33b003aa-7bff-0310-803a-e67f0ece8222 |
---|---|
date | Sun, 29 Jun 2008 18:44:17 +0000 |
parents | |
children | ec653fde64d3 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:4a0efb7baf70 |
---|---|
1 # coding: utf-8 | |
2 | |
3 """ | |
4 Simple error checking attributes. | |
5 | |
6 This module defines a set of Attribute classes | |
7 which you can use to define possible values | |
8 an attribute of an object accepts. | |
9 | |
10 Usage:: | |
11 class SomeObject: | |
12 nameAttr, posAttr = [ Attr("name"), PointAttr("pos") ] | |
13 | |
14 obj = SomeObject() | |
15 obj.nameAttr.set(obj,"newName") | |
16 obj.posAttr.set(obj,"89,89") | |
17 | |
18 This is most useful for error checking parsing and defining | |
19 accepted attributes in classes and is used by pychan internally. | |
20 | |
21 """ | |
22 | |
23 from exceptions import ParserError | |
24 | |
25 class Attr(object): | |
26 """ | |
27 A simple text attribute. | |
28 """ | |
29 def __init__(self,name): | |
30 self.name = name | |
31 | |
32 def set(self,obj,value): | |
33 """ | |
34 Parses the given value with the L{parse} method | |
35 and sets it on the given instance with C{setattr}. | |
36 """ | |
37 value = self.parse(value) | |
38 setattr(obj,self.name,value) | |
39 | |
40 def parse(self,value): | |
41 """ | |
42 Parses a value and checks for errors. | |
43 Override with specialiced behaviour. | |
44 """ | |
45 return str(value) | |
46 | |
47 class PointAttr(Attr): | |
48 def parse(self,value): | |
49 try: | |
50 x,y = tuple(map(int,str(value).split(','))) | |
51 return x,y | |
52 except: | |
53 raise ParserError("Expected a comma separated list of two integers.") | |
54 | |
55 class ColorAttr(Attr): | |
56 def parse(self,value): | |
57 try: | |
58 r,g,b = tuple(map(int,str(value).split(','))) | |
59 except: | |
60 raise ParserError("Expected an color.") | |
61 for c in (r,g,b): | |
62 if not 0 <= c < 256: raise ParserError("Expected a color (Failed: 0 <= %d <= 255)" %c) | |
63 return r,g,b | |
64 | |
65 class IntAttr(Attr): | |
66 def parse(self,value): | |
67 try: | |
68 return int(value) | |
69 except: | |
70 raise ParserError("Expected a single integer.") | |
71 | |
72 class BoolAttr(Attr): | |
73 def parse(self,value): | |
74 try: | |
75 value = int(value) | |
76 if value not in (0,1): | |
77 raise ParserError("Expected a 0 or 1.") | |
78 return value | |
79 except: | |
80 raise ParserError("Expected a 0 or 1.") |