1
2
3
4
5 """
6 Misc utils for internal use
7 """
8
9 __id__ = __revision__ = "$Id: utils.py 28 2006-10-21 08:03:02Z the.pythy $"
10 __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/utils.py $"
11
12 import sys
13
15 """
16 Provide Unicode from text
17
18 @param stext: text
19 @type stext: C{str}
20
21 @param encoding: encoding if input text
22 @type encoding: C{str}
23
24 @return: C{unicode}
25 """
26 try:
27 utext = str(stext).decode(encoding)
28 except UnicodeDecodeError, err:
29 utext = default % {'error': err, 'value': u""}
30 return utext
31
33 """
34 Provide text from Unicode
35
36 @param utext: unicode text
37 @type utext: C{unicode}
38
39 @param encoding: encoding of output text
40 @type encoding: C{str}
41
42 @return: C{str}
43 """
44 try:
45 stext = unicode(utext).encode(encoding)
46 except UnicodeEncodeError, err:
47 stext = default % {'error': err, 'value': ""}
48 return stext
49
51 """
52 Return value of variable by it's name
53
54 @param variable_name: name of variable
55 @type variable_name: C{str}
56
57 @param depth: stack depth
58 @type depth: C{int}
59
60 @raise RuntimeError: when unable to fetch variable
61 """
62 try:
63 variable_value = sys._getframe(depth).f_locals[variable_name]
64 except KeyError:
65 raise RuntimeError("Unable to fetch variable %s (depth %d)" % \
66 (variable_name, depth))
67 return variable_value
68
69
71 """
72 Checks type of variable
73
74 @param variable_name: name of variable
75 @type variable_name: C{str}
76
77 @param typ: type checking for
78 @type typ: C{type} or C{tuple} of types
79
80 @return: None when check successful
81
82 @raise TypeError: check failed
83 """
84 variable_value = get_value_by_name(variable_name, 2)
85 if not isinstance(variable_value, typ):
86 raise TypeError("%s must be %s, not %s" % \
87 (variable_name, str(typ), type(variable_value)))
88
90 """
91 Checks length of variable's value
92
93 @param variable_name: name of variable
94 @type variable_name: C{str}
95
96 @param length: length checking for
97 @type length: C{int}
98
99 @return: None when check successful
100
101 @raise ValueError: check failed
102 """
103 variable_value = get_value_by_name(variable_name, 2)
104 _length = len(variable_value)
105 if _length != length:
106 raise ValueError("%s's length must be %d, but it %d" % \
107 (variable_name, length, _length))
108
110 """
111 Checks if variable is positive
112
113 @param variable_name: name of variable
114 @type variable_name: C{str}
115
116 @return: None when check successful
117
118 @raise ValueError: check failed
119 """
120 variable_value = get_value_by_name(variable_name, 2)
121 if not strict and variable_value < 0:
122 raise ValueError("%s must be positive or zero, not %s" % \
123 (variable_name, str(variable_value)))
124 if strict and variable_value <= 0:
125 raise ValueError("%s must be positive, not %s" % \
126 (variable_name, str(variable_value)))
127