Project

General

Profile

« Previous | Next » 

Revision 278

xml_func.py: Return string->number conversion errors as xml_func.SyntaxExceptions

View differences:

lib/xml_func.py
2 2

  
3 3
import datetime
4 4

  
5
import ex
5 6
import xml_dom
6 7

  
8
class SyntaxException(ex.ExceptionWithCause): pass
9

  
7 10
def map_items(func, items):
8 11
    return [(name, func(value)) for name, value in items]
9 12

  
13
def conv_items(type_, items):
14
    try: return map_items(type_, items)
15
    except ValueError, e: raise SyntaxException(e)
16

  
10 17
def alt(items):
11 18
    items = list(items)
12 19
    items.sort()
13 20
    return items[0][1] # value of lowest-numbered item
14 21

  
15 22
def range_(items):
16
    items = dict(map_items(float, items))
23
    items = dict(conv_items(float, items))
17 24
    return str(items['to'] - items['from'])
18 25

  
19 26
def avg(items):
20 27
    count = 0
21 28
    sum_ = 0.
22
    for name, value in map_items(float, items):
29
    for name, value in conv_items(float, items):
23 30
        count += 1
24 31
        sum_ += value
25 32
    return str(sum_/count)
26 33

  
27 34
def date(items):
28 35
    items = dict(items)
29
    year = float(items['year'])
30
    date = datetime.date(int(year), int(items.get('month', '1')),
31
        int(items.get('day', '1'))) + datetime.timedelta(round((year % 1.)*365))
36
    year = items['year']
37
    month = items.get('month', '1')
38
    day = items.get('day', '1')
39
    try:
40
        year = float(year)
41
        month = int(month)
42
        day = int(day)
43
    except ValueError, e: raise SyntaxException(e)
44
    date = (datetime.date(int(year), month, day) +
45
        datetime.timedelta(round((year % 1.)*365)))
32 46
    return date.strftime('%Y-%m-%d')
33 47

  
34 48
def name(items):

Also available in: Unified diff