~ubuntu-branches/ubuntu/hardy/gnue-common/hardy

« back to all changes in this revision

Viewing changes to src/apps/checktype.py

  • Committer: Bazaar Package Importer
  • Author(s): Andrew Mitchell
  • Date: 2005-03-09 11:06:31 UTC
  • Revision ID: james.westby@ubuntu.com-20050309110631-8gvvn39q7tjz1kj6
Tags: upstream-0.5.14
ImportĀ upstreamĀ versionĀ 0.5.14

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# GNU Enterprise Common Library - checktype support
 
2
#
 
3
# This file is part of GNU Enterprise.
 
4
#
 
5
# GNU Enterprise is free software; you can redistribute it
 
6
# and/or modify it under the terms of the GNU General Public
 
7
# License as published by the Free Software Foundation; either
 
8
# version 2, or (at your option) any later version.
 
9
#
 
10
# GNU Enterprise is distributed in the hope that it will be
 
11
# useful, but WITHOUT ANY WARRANTY; without even the implied
 
12
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 
13
# PURPOSE. See the GNU General Public License for more details.
 
14
#
 
15
# You should have received a copy of the GNU General Public
 
16
# License along with program; see the file COPYING. If not,
 
17
# write to the Free Software Foundation, Inc., 59 Temple Place
 
18
# - Suite 330, Boston, MA 02111-1307, USA.
 
19
#
 
20
# Copyright 2001-2005 Free Software Foundation
 
21
#
 
22
# $Id: checktype.py 6851 2005-01-03 20:59:28Z jcater $
 
23
"""
 
24
Support for checking the type of variables
 
25
"""
 
26
from types import *
 
27
 
 
28
import string
 
29
import sys
 
30
 
 
31
from gnue.common.apps import i18n
 
32
 
 
33
# -----------------------------------------------------------------------------
 
34
# Exceptions
 
35
# -----------------------------------------------------------------------------
 
36
 
 
37
class TypeError (Exception):
 
38
  """
 
39
  Raised when L{checktype} detects a wrong type.
 
40
 
 
41
  Do not raise this exception manually.
 
42
  """
 
43
 
 
44
# -----------------------------------------------------------------------------
 
45
 
 
46
  def __stringify (self, atype):
 
47
    if isinstance (atype, ListType):
 
48
      return string.join ([self.__stringify (t) for t in atype], ' / ')
 
49
    elif isinstance (atype, TypeType):
 
50
      return str (atype)
 
51
    elif isinstance (atype, ClassType):
 
52
      return '<class %s>' % str (atype)
 
53
    else:
 
54
      return '<type %s>' % str (atype)
 
55
 
 
56
# -----------------------------------------------------------------------------
 
57
 
 
58
  def __init__ (self, variable, expected):
 
59
 
 
60
    self.varname = '<?>'
 
61
    for (k, v) in (sys._getframe (2)).f_locals.items ():
 
62
      if variable is v:
 
63
        self.varname = k
 
64
 
 
65
    self.expected = expected            # Expected type of variable
 
66
 
 
67
    if isinstance (variable, InstanceType):
 
68
      self.actual = variable.__class__
 
69
    else:
 
70
      self.actual = type (variable)     # Actual type of variable
 
71
 
 
72
    self.value = variable               # Value of variable
 
73
 
 
74
    message = u_('"%(varname)s" is expected to be of %(expected)s but is of '
 
75
                 '%(actual)s and has value %(value)s') \
 
76
              % {'varname' : self.varname,
 
77
                 'expected': self.__stringify (self.expected),
 
78
                 'actual'  : self.__stringify (self.actual),
 
79
                 'value'   : repr (self.value)}
 
80
    Exception.__init__ (self, message)
 
81
 
 
82
# -----------------------------------------------------------------------------
 
83
# Check type of a variable
 
84
# -----------------------------------------------------------------------------
 
85
 
 
86
def checktype (variable, validtype):
 
87
  """
 
88
  Check a varaible (for example a parameter to a function) for a correct type.
 
89
 
 
90
  This function is available as builtin function.
 
91
 
 
92
  @param variable: the variable to check
 
93
  @param validtype: the type, the class, or a list of types and classes that
 
94
    are valid
 
95
  """
 
96
  if isinstance (validtype, ListType):
 
97
    for t in validtype:
 
98
      if isinstance (variable, t):
 
99
        return
 
100
  else:
 
101
    if isinstance (variable, validtype):
 
102
      return
 
103
  raise TypeError, (variable, validtype)
 
104
 
 
105
# -----------------------------------------------------------------------------
 
106
# Module initialization
 
107
# -----------------------------------------------------------------------------
 
108
 
 
109
import __builtin__  
 
110
__builtin__.__dict__['checktype'] = checktype
 
111
 
 
112
# -----------------------------------------------------------------------------
 
113
# Self test code
 
114
# -----------------------------------------------------------------------------
 
115
 
 
116
if __name__ == '__main__':
 
117
 
 
118
  import sys
 
119
 
 
120
  def mustfail (testvar, validtype):
 
121
    try:
 
122
      checktype (testvar, validtype)
 
123
    except TypeError, message:
 
124
      print message
 
125
      return
 
126
    raise Error ("checking %s as %s hasn't failed!" % (repr (variable),
 
127
                                                       repr (validtype)))
 
128
 
 
129
  n = None
 
130
  s = 'this is a string'
 
131
  u = u'this is a unicode string'
 
132
  i = 100
 
133
  f = 17.85
 
134
  class p:
 
135
    pass
 
136
  class c (p):
 
137
    pass
 
138
  o = c ()
 
139
 
 
140
  print 'Single type, success ...'
 
141
  checktype (n, NoneType)
 
142
  checktype (s, StringType)
 
143
  checktype (u, UnicodeType)
 
144
  checktype (i, IntType)
 
145
  checktype (f, FloatType)
 
146
  checktype (c, ClassType)
 
147
  checktype (o, InstanceType)
 
148
  checktype (o, c)
 
149
  checktype (o, p)
 
150
 
 
151
  print 'Multiple types, success ...'
 
152
  checktype (n, [StringType, NoneType])
 
153
  checktype (s, [StringType, UnicodeType])
 
154
  checktype (u, [StringType, UnicodeType])
 
155
  checktype (o, [NoneType, c])
 
156
 
 
157
  print 'Single type, failure ...'
 
158
  mustfail (n, StringType)
 
159
  mustfail (s, UnicodeType)
 
160
  mustfail (u, StringType)
 
161
  mustfail (i, FloatType)
 
162
  mustfail (o, IntType)
 
163
  mustfail (c, c)
 
164
 
 
165
  print 'Multiple types, failure ...'
 
166
  mustfail (n, [StringType, UnicodeType])
 
167
  mustfail (s, [IntType, FloatType])
 
168
 
 
169
  print 'All test passed.'