File: Type.py

package info (click to toggle)
atheist 0.20110402-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,348 kB
  • sloc: python: 4,764; xml: 626; makefile: 113; cpp: 54; ansic: 5; sh: 5
file content (439 lines) | stat: -rw-r--r-- 11,715 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# -*- mode: python; coding: utf-8 -*-

"""types module provides more powerful structures and functions than built-in

.. moduleauthor:: Arco Research Group

"""

import string, csv
import inspect
import warnings
import collections


class Record(object):
    "kargs are automatic attributes"

    def __init__(self, **kargs):
        self._attrs = kargs.keys()

        for k,v in kargs.items():
            setattr(self, k, v)

    def __str__(self):
        retval = ""
        for k in self._attrs:
            retval += "%s:'%s' " % (k, getattr(self, k))

        return "<Record %s>" % retval


# FIXME: probaly may be replaced with collections.OrderedDict in python2.7
# iniparse has a simpler SortedDict
class SortedDict(dict):
    """A fixed-position dictionary. The keys will be stored on a list in the
    same order as are inserted."""

    def __init__(self, other={}, default=None, **kargs):
        self.__keylist = []
        self.default = default
        if isinstance(other, dict):
            self.update(other)
        if isinstance(other, list):
            for key,val in other:
                self[key] = val

        for k,v in kargs.items():
            self[k] = v

    def __getitem__(self, key):
        if not key in dict.keys(self):
            if self.default is None:
                raise KeyError(key)

            self[key] = self.default

        return dict.__getitem__(self, key)


    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        if key in self.__keylist:
            self.__keylist.remove(key)
        self.__keylist.append(key)


    def update(self, other):
        for k,v in other.items():
            self[k] = v


    def keys(self):
        return self.__keylist


    def values(self):
        return [self[k] for k in self.__keylist]


    def items(self):
        return [(k, self[k]) for k in self.__keylist]


    def __iter__(self):
        return self.__keylist.__iter__()


    def clear(self):
        self.__keylist = []
        dict.clear(self)






#
# DEPRECATED: Use 'default' param in SortedDict
#
#class ListDict(SortedDict):
#    """A special case of a SortedDict. Here, if a key is unknown, it is created
#    en empty list for it."""
#
#    def __getitem__(self, key):
#        if not key in dict.keys(self):
#            self[key] = []
#        return SortedDict.__getitem__(self, key)


class DictTemplate:
    '''Read a template from file and generate a dict allowing substitutions

    template_file:
       full_name = Mr. $firstname %surname
       The $title = $value

    dt = DictTemplate('template_file', delimiter='=')
    result = t.substitute(dict(firstname='John', surname='Doe', title='job', value='fireman'))
    DictTemplate.render(result, 'out_file')

    out_file:
       full_name = Mr. John Doe
       The job = fireman
    '''

    def __init__(self, file_, delimiter=','):
        if isinstance(file_, str):
            self.fd = open(file_)
        else:
            self.fd = file_

        self.delimiter = delimiter

    def substitute(self, values):
        self.fd.seek(0)
        result = string.Template(self.fd.read()).safe_substitute(values)

        csv_file = csv.reader(result.split('\n'), delimiter=self.delimiter)

        retval = SortedDict()
        for row in csv_file:
            if not row or len(row) < 2: continue

            if any(['$' in x for x in row]): continue
            retval[row[0].strip()] = self.delimiter.join((row[1:])).strip()

        return retval

    @classmethod
    def render(cls, data, fname, delimiter=','):
        """Render dict 'data' for file 'fname' using 'delimiter' """
        assert isinstance(data, dict)

        with file(fname, 'w') as fd:
            for x in data.items():
                fd.write("%s = %s\n" % x)


def striplit(val, sep=' ', require_len=None):
    '''
    >>> striplit(' this -  is a -  sample  ', sep='-')
    ['this', 'is a', 'sample']
    '''

    val = val.strip(sep)
    retval = [x.strip() for x in val.split(sep)]
    if require_len is not None and len(retval) != require_len:
        raise ValueError("Incorrect size != %s" % require_len)
    return retval


def uniq(alist):
    '''
    >>> list(uniq([1, 2, 2, 3, 2, 3, 5]))
    [1, 2, 3, 5]
    '''

    s = set()
    for i in alist:
        if i in s: continue
        s.add(i)
        yield i


def merge(*input):
    """
    >>> merge([1,2], [2,4], [5, 6])
    [1, 2, 2, 4, 5, 6]
    >>> merge([[1,2], [2,4]])
    [[1, 2], [2, 4]]
    >>> merge(*[[1,2], [2,4]])
    [1, 2, 2, 4]
    """
    return reduce(list.__add__, input, list())


def merge_uniq(*input):
    """
    >>> merge_uniq([1,2], [2,4], [5, 6])
    [1, 2, 4, 5, 6]
    >>> merge_uniq([1,2])
    [1, 2]
    >>> merge_uniq(*[[1,2], [2,4]])
    [1, 2, 4]
    >>> merge_uniq([1, 2, 2, 3, 2, 3, 5])
    [1, 2, 3, 5]
    """
    return list(set(merge(*input)))


def get_supercls(cls):
    "Returns all ancestor superclasses as a list"
    return [cls] + merge(*[get_supercls(x) for x in cls.__bases__])


class FullWrapper(object):
    '''
    Simple modification over:

    module: method_decorator
    author: denis@ryzhkov.org
    license: free
    url: http://denis.ryzhkov.org/soft/python_lib/method_decorator.py

    Usage:
        class my_dec(method_decorator):
            def pre(self, function, *args, **kwargs):
                print 'calling', function

        @my_dec
        def func_or_method(...)
    '''

    def __init__(self, func, obj=None, cls=None, method_type='function'):
        self.func = func
        self.obj = obj
        self.cls = cls
        self.method_type = method_type

    def __get__(self, obj=None, cls=None):
        if self.obj == obj and self.cls == cls:
            return self

        if isinstance(self.func, staticmethod):
            method_type = 'staticmethod'
        elif isinstance(self.func, classmethod):
            method_type = 'classmethod'
        else:
            method_type = 'instancemethod'

        return object.__getattribute__(self, '__class__')(
            self.func.__get__(obj, cls), obj, cls, method_type)

    def __call__(self, *args, **kwargs):
        self.decoration(self.func, *args, **kwargs)
        return self.func(*args, **kwargs)

    def decoration(self, func, *args, **kargs):
        pass

    def __getattribute__(self, attr_name):
        if attr_name in ('__init__', '__get__', '__call__', '__getattribute__',
                         'func', 'obj', 'cls', 'decoration', 'method_type'):

            return object.__getattribute__(self, attr_name)

        return getattr(self.func, attr_name)

    def __repr__(self):
        return self.func.__repr__()


class accept:

    level = 'error'  # None, 'error', 'warn'

    def __init__(self, *types_as_values, **types_as_dict):
        self.types_as_values = types_as_values
        self.types_as_dict = types_as_dict

        if self.level is None:
            return

        class decorator(FullWrapper):
            def decoration(deco, function, *args, **kargs):
                self.check_types(deco, function, *args, **kargs)

        self.__call__ = decorator


    def __call__(self, function):
        'no decoration by default'
        return function


    def check_types(self, deco, function, *args, **kargs):

        def typerepr(typespec):
            if isinstance(typespec, type):
                return typespec.__name__

            if isinstance(typespec, tuple):
                return str.join('/', [typerepr(x) for x in typespec])

            raise TypeError, "'{0}' is not a type or tuple of types".format(typespec)


        def get_argspec():
            args, varargs, keywords, defaults = inspect.getargspec(function)
            if deco.method_type in ['instancemethod', 'classmethod']:
                args = args[1:] #skip self/cls

            return inspect.ArgSpec(args, varargs, keywords, defaults)


        def get_type_map():
            if self.types_as_dict:
                if self.types_as_values:
                    self.error("mix key and non-key args is forbidden")
                return self.types_as_dict

            if len(spec.args) != len(self.types_as_values):
                self.error("{0}() takes {1} arguments ({2} types given)".format(
                    function.__name__, len(spec.args), len(self.types_as_values)))

            return dict(zip(spec.args, self.types_as_values))


        def check_type_map():
            for arg_name in types_map.keys():
                if not arg_name in spec.args and arg_name != spec.varargs:
                    self.error("{0}() has not an argument '{1}'".format(
                            function.__name__, arg_name))


        def check_args():
#            print 'args 1:%s %s' % (len(args), args[1:])


            for i,arg_name in enumerate(spec.args):
                try:
                    value = kargs[arg_name]
                except KeyError:
                    try:
                        value = args[i]
                    except IndexError:
                        continue

                try:
                    expected_type = types_map[arg_name]
                except KeyError:
                    continue

#                print "%s %s '%s' %s" % (i, arg_name, value, expected_type)

                if not isinstance(value, expected_type):
                    self.error("Argument '{0}' should be '{1}' ('{2}' given)".format(\
                        arg_name, typerepr(expected_type), type(value).__name__))


        def check_varargs():
            if not spec.varargs: return
#           print types_map

            expected_type = types_map[spec.varargs]

            for value in args[len(spec.args):]:
                if not isinstance(value, expected_type):
                    self.error("Argument '{0}' should be '{1}' ('{2}' given)".format(\
                            value, expected_type.__name__, type(value).__name__))



        spec = get_argspec()
#        print spec

        types_map = get_type_map()
#        print types_map

        check_type_map()
        check_args()
        check_varargs()


    @classmethod
    def error(cls, msg):
        if cls.level == 'error':
            raise TypeError, msg

        if cls.level == 'warn':
            warnings.warn(msg, RuntimeWarning)
            return

        raise TypeError, "accept.level must be one of ['error', 'warn', None]"


def attributes(*arg_names):

    class decorator(FullWrapper):
        def decoration(self, function, *args, **kargs):

#            print inspect.getargspec(function)
            formal_args = inspect.getargspec(function).args[1:] # skip self

            defaults = inspect.getargspec(function).defaults or []
            n_positionals = len(formal_args) - len(defaults)

            for name in arg_names:
                if not name in formal_args:
                    raise TypeError, "'{0}()' method has no argument '{1}'".format(
                        function.__name__, name)

                pos = formal_args.index(name)

#                print "--\n%s %s %s" % (name, pos, n_positionals)
#                print args
#                print kargs


                try:
                    value = args[pos]
                except IndexError:
                    try:
                        value = kargs[name]
                    except KeyError:
                        value = defaults[pos-n_positionals]

                setattr(self.obj, name, value)


    return decorator


def check_type(val, cls):
    if not isinstance(val, cls):
        raise TypeError(("A %s is required, not %s." % \
              (cls.__name__, val.__class__.__name__)))

    return val