specificator.py 21.8 KB
Newer Older
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
1
# -*- coding: utf-8 -*-
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
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
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

35
36
from random import random, choice, randint
from math import log
37
from inspect import isclass
38
from .utils.argmap import argmap_decode, argmap_check, argmap_dict_to_list
39
40
41
42

try:
    from collections import OrderedDict
except ImportError:
43
    from .utils.ordereddict import OrderedDict
44
45
46
47
48
49
50
51
52

def shorts(s):
    if not isinstance(s, unicode):
        s = str(s)

    if len(s) <= 64:
        return s

    return s[:61] + '...'
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
53

54
55
56
57
58
59
60
61
62

class CanonifyException(Exception):
    pass

class SpecifyException(Exception):
    pass


class Canonical(object):
63
64
65

    random_choice = None

66
    def __init__(self, *args, **kw):
67
68
69
70
71
72
73
        self.args = []
        named_args = []
        for a in args:
            if isinstance(a, tuple) and len(a) == 2:
                named_args.append(a)
            else:
                self.args.append(a)
74
        ordered_dict = OrderedDict(named_args)
75

76
        self.name = kw.pop('classname', self.__class__.__name__)
77
78
79
        random_choice = kw.pop('random', None)
        if random_choice is not None:
            self.random_choice = random_choice
80
81
82
        opts = {}
        for k, v in kw.items():
            if not isinstance(v, Canonical):
83
84
85
86
87
                if isclass(v) and issubclass(v, Canonical):
                    m = ("argument '%s': value '%s' is a Canonical _class_. "
                         "Perhaps you meant to specify a Canonical _instance_"
                         % (k, v))
                    raise SpecifyException(m)
88
89
90
91
                opts[k] = v
                del kw[k]

        self.opts = opts
92
93
        ordered_dict.update(kw)
        self.kw = ordered_dict
94
95
96
97
98
99
100
        self.init()

        if 'default' in opts:
            item = opts['default']
            if item is None:
                opts['null'] = 1
            else:
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
101
                opts['default'] = self._check(item)
102
103
104
105
106

    def init(self):
        return

    def __call__(self, item):
107
108
109
        return self.check(item)

    def check(self, item):
110
111
112
113
114
115
116
117
        opts = self.opts
        if item is None and 'default' in opts:
            item = opts['default']

        can_be_null = opts.get('null', False)
        if item is None and can_be_null:
            return None

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
118
119
120
        if argmap_check(item):
            item = self._unpack(item)

121
        return self._check(item)
122

123
    def _check(self, item):
124
125
        return item

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
126
127
128
129
130
131
    def _unpack(self, item):
        argmap = argmap_list_to_dict(item)
        if len(argmap) == 2:
            return argmap[None]
        return argmap

132
133
134
    def create(self):
        return None

135
136
137
138
139
140
141
142
143
144
145
146
    def random(self, **kw):
        random_choice = self.random_choice
        if random_choice is None:
            return None

        if callable(random_choice):
            return random_choice(kw)

        if isinstance(random_choice, str):
            return getattr(self, random_choice)(kw)

        return choice(random_choice)
147

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    def tostring(self, depth=0, showopts=0, multiline=0):
        depth += 1
        if not multiline:
            argdepth = ''
            owndepth = ''
            joinchar = ','
            padchar = ''
        else:
            argdepth = '    ' * depth
            owndepth = '    ' * (depth - 1)
            joinchar = ',\n'
            padchar = '\n'

        args = [a.tostring( depth=depth,
                            showopts=showopts,
                            multiline=multiline) for a in self.args]
        args += [("%s=%s" %
                    (k, v.tostring( depth=depth,
                                    showopts=showopts,
                                    multiline=multiline)))
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
168

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
                                    for k, v in self.kw.items()]
        if showopts:
            args += [("%s=%s" % (k, str(v))) for k, v in self.opts.items()]

        if len(args) == 0:
            string = "%s(%s)" % (self.name, ','.join(args))
        else:
            string = "%s(%s" % (self.name, padchar)
            for arg in args:
                string += argdepth + arg + joinchar
            string = string[:-1] + padchar
            string += owndepth + ")"

        return string

    __str__ = tostring

    def __repr__(self):
        return self.tostring(multiline=0, showopts=1)

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
189
190
191
192
193
194
    def show(self):
        showable = self.opts.get('show', True)
        return self._show() if showable else ''

    def _show(self):
        return self.name
195
196
197

class Null(Canonical):

198
    def _check(self, item):
199
200
201
202
        return None

Nothing = Null()

203

204
205
class Integer(Canonical):

206
    def _check(self, item):
207
        try:
208
            num = long(item)
209
210
        except ValueError, e:
            try:
211
                num = long(item, 16)
212
            except Exception:
213
                m = "%s: cannot convert '%s' to long" % (self, shorts(item))
214
                raise CanonifyException(m)
215
216
        except TypeError, e:
            m = "%s: cannot convert '%s' to long" % (self, shorts(item))
217
            raise CanonifyException(m)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

        optget = self.opts.get
        minimum = optget('minimum', None)
        maximum = optget('maximum', None)

        if minimum is not None and num < minimum:
            m = "%s: %d < minimum=%d" % (self, num, minimum)
            raise CanonifyException(m)

        if maximum is not None and num > maximum:
            m = "%s: %d > maximum=%d" % (self, num, maximum)
            raise CanonifyException(m)

        return num

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    def random_integer(self, kw):
        optget = self.opts.get
        kwget = kw.get
        minimum = kwget('minimum', optget('minimum', -4294967296L))
        maximum = kwget('maximum', optget('maximum', 4294967295L))
        r = random()
        if r < 0.1:
            return minimum
        if r < 0.2:
            return maximum
        if minimum <= 0 and maximum >= 0 and r < 0.3:
            return 0L
        return long(minimum + r * (maximum - minimum))

    random_choice = random_integer


250

251
252
253
254
255
256
Serial = Integer(
            classname   =   'Serial',
            null        =   True,
)


257
class Text(Canonical):
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278

    re = None
    matcher = None
    choices = None

    def init(self):
        opts = self.opts
        if 'regex' in opts:
            pat = opts['regex']
            re = self.re
            if re is None:
                import re
                self.re = re

            self.matcher = re.compile(pat, re.UNICODE)
            self.pat = pat

        if 'choices' in opts:
            opts['choices'] = dict((unicode(x), unicode(x))
                                    for x in opts['choices'])

279
    def _check(self, item):
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
        if not isinstance(item, unicode):
            # require non-unicode items to be utf8
            item = str(item)
            try:
                item = item.decode('utf8')
            except UnicodeDecodeError, e:
                item = item.decode('latin1')
                m = "%s: non-unicode '%s' is not utf8" % (self, shorts(item))
                raise CanonifyException(m)

        opts = self.opts
        if 'choices' in opts:
            choices = opts['choices']
            try:
                unknown = item not in choices
            except TypeError, e:
                m = "%s: unhashable type '%s'" % (self.name, shorts(item))
                raise CanonifyException(m, e)

            if unknown:
                m = "%s: '%s' not in choices" % (self.name, shorts(item))
                raise CanonifyException(m)

            return choices[item]

        optget = opts.get
        itemlen = len(item)
        maxlen = optget('maxlen', None)
        if maxlen is not None and itemlen > maxlen:
            m = "%s: len('%s') > maxlen=%d" % (self, shorts(item), maxlen)
            raise CanonifyException(m)

        minlen = optget('minlen', None)
        if minlen is not None and itemlen < minlen:
            m = "%s: len('%s') < minlen=%d" % (self, shorts(item), minlen)
            raise CanonifyException(m)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
316

317
318
319
320
321
322
323
324
325
326
327
328
        matcher = self.matcher
        if matcher is not None:
            match = matcher.match(item)
            if  (       match is None
                    or  (match.start(), match.end()) != (0, itemlen)    ):

                    m = ("%s: '%s' does not match '%s'"
                            % (self, shorts(item), self.pat))
                    raise CanonifyException(m)

        return item

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
    default_alphabet = '0123456789αβγδεζ'.decode('utf8')

    def random_string(self, kw):
        opts = self.opts
        if 'regex' in opts:
            m = 'Unfortunately, random for regex strings not supported'
            raise ValueError(m)

        optget = opts.get
        kwget = kw.get
        minlen = kwget('minlen', optget('minlen', 0))
        maxlen = kwget('maxlen', optget('maxlen', 32))
        alphabet = kwget('alphabet', self.default_alphabet)
        z = maxlen - minlen
        if z < 1:
            z = 1

        g = log(z, 2)
        r = random() * g
        z = minlen + int(2**r)

        s = u''
        for _ in xrange(z):
            s += choice(alphabet)

        return s

    random_choice = random_string

358

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
class Bytes(Canonical):

    re = None
    matcher = None
    choices = None

    def init(self):
        opts = self.opts
        if 'regex' in opts:
            pat = opts['regex']
            re = self.re
            if re is None:
                import re
                self.re = re

            self.matcher = re.compile(pat)
            self.pat = pat

        if 'choices' in opts:
            opts['choices'] = dict((str(x), str(x))
                                    for x in opts['choices'])

381
    def _check(self, item):
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
        if isinstance(item, unicode):
            # convert unicode to utf8
            item = item.encode('utf8')

        opts = self.opts
        if 'choices' in opts:
            choices = opts['choices']
            try:
                unknown = item not in choices
            except TypeError, e:
                m = "%s: unhashable type '%s'" % (self.name, shorts(item))
                raise CanonifyException(m, e)

            if unknown:
                m = "%s: '%s' not in choices" % (self.name, shorts(item))
                raise CanonifyException(m)

            return choices[item]

        optget = opts.get
        itemlen = len(item)
        maxlen = optget('maxlen', None)
        if maxlen is not None and itemlen > maxlen:
            m = "%s: len('%s') > maxlen=%d" % (self, shorts(item), maxlen)
            raise CanonifyException(m)

        minlen = optget('minlen', None)
        if minlen is not None and itemlen < minlen:
            m = "%s: len('%s') < minlen=%d" % (self, shorts(item), minlen)
            raise CanonifyException(m)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
        matcher = self.matcher
        if matcher is not None:
            match = matcher.match(item)
            if  (       match is None
                    or  (match.start(), match.end()) != (0, itemlen)    ):

                    m = ("%s: '%s' does not match '%s'"
                            % (self, shorts(item), self.pat))
                    raise CanonifyException(m)

        return item

    default_alphabet = '0123456789abcdef'

    def random_bytes(self, kw):
        opts = self.opts
        if 'regex' in opts:
            m = 'Unfortunately, random for regex strings not supported'
            raise ValueError(m)

        optget = opts.get
        kwget = kw.get
        minlen = kwget('minlen', optget('minlen', 0))
        maxlen = kwget('maxlen', optget('maxlen', 32))
        alphabet = kwget('alphabet', self.default_alphabet)
        z = maxlen - minlen
        if z < 1:
            z = 1

        g = log(z, 2)
        r = random() * g
        z = minlen + int(2**r)

        s = u''
        for _ in xrange(z):
            s += choice(alphabet)

        return s

    random_choice = random_bytes


455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
class ListOf(Canonical):

    def init(self):
        args = self.args
        kw = self.kw

        if not (args or kw):
            raise SpecifyException("ListOf requires one or more arguments")

        if args and kw:
            m = ("ListOf requires either positional "
                 "or keyword arguments, but not both")
            raise SpecifyException(m)

        if args:
            if len(args) > 1:
                self.canonical = Tuple(*args)
            else:
                self.canonical = args[0]
        else:
            self.canonical = Args(**kw)

477
    def _check(self, item):
478
479
480
481
482
483
        if item is None:
            item = ()

        try:
            items = iter(item)
        except TypeError, e:
484
            m = "%s: %s is not iterable" % (self, shorts(item))
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
            raise CanonifyException(m)

        canonical = self.canonical
        canonified = []
        append = canonified.append

        for item in items:
            item = canonical(item)
            append(item)

        if not canonified and self.opts.get('nonempty', False):
            m = "%s: must be nonempty" % (self,)
            raise CanonifyException(m)

        return canonified

501
502
503
504
505
506
507
508
    def random_listof(self, kw):
        z = randint(1, 4)
        get_random = self.canonical.random

        return [get_random() for _ in xrange(z)]

    random_choice = random_listof

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
509
510
    def _show(self):
        return '[ ' + self.canonical.show() + ' ... ]'
511
512
513

class Args(Canonical):

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
514
515
516
    def _unpack(self, arglist):
        return arglist

517
518
519
520
521
    def _check(self, item):
        if argmap_check(item):
            if hasattr(item, 'keys') and callable(item.keys):
                arglist = argmap_dict_to_list(item)[:-1]
            else:
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
522
                arglist = item[:-1]
523
524
525
526
527
528
        else:
            try:
                arglist = OrderedDict(item).items()
            except (TypeError, ValueError), e:
                m = "%s: %s is not dict-able" % (self, shorts(item))
                raise CanonifyException(m)
529

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
530
        keys = self.kw.keys()
531
532
533
534
535
536
537
538
        kw = self.kw
        arglen = len(arglist)
        if arglen != len(keys):
            m = "inconsistent number of parameters: %s != %s" % (
                arglen, len(keys))
            raise CanonifyException(m)

        canonified = OrderedDict()
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
539
540
541
        position = 0

        for k, v in arglist:
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
542
            if k is not None:
543
                canonified[k] = kw[k].check(v)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
544
545
546
547
            else:
                # find the right position
                for i in range(position, arglen):
                    key = keys[i]
548
                    if not key in canonified.keys():
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
549
550
551
552
                        position = i + 1
                        break
                else: # exhausted
                    raise Exception("shouldn't happen")
553
                canonified[key] = kw[key].check(v)
554
555
556

        return canonified

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
557
558
559
560
    def _show(self):
        strings = [x for x in [c.show() for n, c in self.kw.items()] if x]
        return ' '.join(strings)

561
562
    def random_args(self, kw):
        args = {}
563
        for n, c in self.kw.items():
564
565
566
567
568
            args[n] = c.random()
        return args

    random_choice = random_args

569
570
571

class Tuple(Canonical):

572
    def _check(self, item):
573
574
575
        try:
            items = list(item)
        except TypeError, e:
576
            m = "%s: %s is not iterable" % (self, shorts(item))
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
            raise CanonifyException(m)

        canonicals = self.args
        zi = len(items)
        zc = len(canonicals)

        if zi != zc:
            m = "%s: expecting %d elements, not %d (%s)" % (self, zc, zi, str(items))
            raise CanonifyException(m)

        g = (canonical(element) for canonical, element in zip(self.args, item))

        return tuple(g)

    def __add__(self, other):
        oargs = other.args if isinstance(other, Tuple) else (other,)
        args = self.args + oargs
        return self.__class__(*args)

596
597
598
599
600
    def random_tuple(self, kw):
        return tuple(c.random() for c in self.args)

    random_choice = random_tuple

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
601
602
603
604
    def _show(self):
        canonicals = self.args
        strings = [x for x in [c.show() for c in canonicals] if x]
        return '[ ' + ' '.join(strings) + ' ]'
605
606
607

class Dict(Canonical):

608
    def _check(self, item):
609
610
611
612
613
614
615
616

        try:
            item = dict(item)
        except TypeError:
            m = "%s: '%s' is not dict-able" % (self, shorts(item))
            raise CanonifyException(m)

        canonified = {}
617
618
619
620
621
622
        canonical = self.kw

        for n, c in canonical.items():
            if n not in item:
                m = "%s: key '%s' not found" % (self, shorts(n))
                raise CanonifyException(m)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
623
            canonified[n] = c(item[n])
624

625
        strict = self.opts.get('strict', True)
626
627
628
629
630
631
        if strict and len(item) != len(canonical):
            for k in sorted(item.keys()):
                if k not in canonical:
                    break

            m = "%s: unexpected key '%s' (strict mode)" % (self, shorts(k))
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
632
633
634
            raise CanonifyException(m)

        return canonified
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
635

636
637
    def random_dict(self, kw):
        item = {}
638
        for n, c in self.canonical.items():
639
640
641
642
643
644
            item[n] = c.random()

        return item

    random_choice = random_dict

645
646

class Canonifier(object):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
647
    def __init__(self, name, input_canonicals, output_canonicals, doc_strings):
648
649
650
        self.name = name
        self.input_canonicals = dict(input_canonicals)
        self.output_canonicals = dict(output_canonicals)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
651
        self.doc_strings = dict(doc_strings)
652
653
654
655

    def call_names(self):
        return self.input_canonicals.keys()

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
656
657
658
659
    def call_docs(self):
        for call_name, call_doc in self.doc_strings.iteritems():
            yield call_name, call_doc

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
660
661
662
663
664
665
666
    def get_doc(self, name):
        if name not in self.doc_strings:
            m = "%s: Invalid method name '%s'" % (self.name, name)
            raise CanonifyException(m)

        return self.doc_strings[name]

667
668
669
670
    def call_attrs(self):
        for call_name, canonical in self.input_canonicals.iteritems():
            yield call_name, canonical.tostring(showopts=1, multiline=1)

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
    def input_canonical(self, name):
        input_canonicals = self.input_canonicals
        if name not in input_canonicals:
            m = "%s: Invalid input call '%s'" % (self.name, name)
            raise CanonifyException(m)

        return input_canonicals[name]

    def canonify_input(self, name, the_input):
        return self.input_canonical(name)(the_input)

    def output_canonical(self, name):
        output_canonicals = self.output_canonicals
        if name not in output_canonicals:
            m = "%s: Output canonical '%s' does not exist" % (self.name, name)
            raise CanonifyException(m)

        return output_canonicals[name]

    def canonify_output(self, name, the_output):
        return self.output_canonical(name)(the_output)

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
693
694
695
    def show_input_canonical(self, name):
        return self.input_canonical(name).show()

696
    def parse(self, method, arglist):
697
        args, rest = argmap_decode(arglist)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
698
        return self.input_canonical(method).check(args)
699

700
701
702
703
704
705
706
707
708
709
710
711

class Specificator(object):

    def __new__(cls):
        if cls is Specificator:
            m = "Specificator classes must be subclassed"
            raise SpecifyException(m)

        import inspect

        canonical_inputs = {}
        canonical_outputs = {}
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
712
        doc_strings = {}
713
714
715
716
717
718

        for name in dir(cls):
            f = getattr(cls, name)
            if not inspect.ismethod(f) or f.__name__.startswith('_'):
                continue

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
719
            doc_strings[name] = f.__doc__
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
            argspec = inspect.getargspec(f)
            defaults = argspec.defaults
            args = argspec.args
            if args and args[0] == 'self':
                args = args[1:]

            if not defaults:
                defaults = ()

            arglen = len(args)
            deflen = len(defaults)

            if arglen != deflen:
                a = (f.__name__, args[:arglen-deflen])
                m = "Unspecified arguments in '%s': %s" % a
                raise SpecifyException(m)

737
738
            args = zip(args, defaults)
            for a, c in args:
739
740
741
742
743
                if not isinstance(c, Canonical):
                    m = ("argument '%s=%s' is not an instance of 'Canonical'"
                         % (a, repr(c)))
                    raise SpecifyException(m)

744
            canonical = Null() if len(args) == 0 else Args(*args)
745
746
747
748
749
            canonical_inputs[name] = canonical

            self = object.__new__(cls)
            canonical = f(self)
            if not isinstance(canonical, Canonical):
750
751
                m = ("method '%s' does not return a Canonical, but a(n) %s "
                                                    % (name, type(canonical)))
752
753
754
                raise SpecifyException(m)
            canonical_outputs[name] = canonical

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
755
756
        return Canonifier(cls.__name__, canonical_inputs, canonical_outputs,
                          doc_strings)
757
758
759
760

    def __call__(self):
        return self