Author: reinhard Date: 2009-10-02 04:47:54 -0500 (Fri, 02 Oct 2009) New Revision: 9920
Added: trunk/gnue-common/src/lib/checktype.py Removed: trunk/gnue-common/src/apps/checktype.py trunk/gnue-common/src/base/checktype.py Modified: trunk/gnue-common/src/apps/__init__.py trunk/gnue-common/tests/apps_checktype.py Log: Reworked checktype to be more generally usable (not GNUe dependent), moved it to lib. Modified: trunk/gnue-common/src/apps/__init__.py =================================================================== --- trunk/gnue-common/src/apps/__init__.py 2009-10-01 13:51:39 UTC (rev 9919) +++ trunk/gnue-common/src/apps/__init__.py 2009-10-02 09:47:54 UTC (rev 9920) @@ -30,9 +30,10 @@ import GDebug import __builtin__ +from gnue.common.lib import checktype + from gnue.common.apps import i18n from gnue.common.apps import errors -from gnue.common.apps import checktype # ----------------------------------------------------------------------------- @@ -43,15 +44,3 @@ print ' * %s' % text __builtin__.__dict__['gStartupStatus'] = _print_startup_status - - - -# Add the decimal class for python 2.3 or less -#if sys.hexversion < 0x02040000: -# pth = sys.path -# from gnue.common.external import decimal -# sys.modules['decimal'] = decimal -#else: -# import decimal -# -#__builtins__['Decimal'] = decimal.Decimal Deleted: trunk/gnue-common/src/apps/checktype.py =================================================================== --- trunk/gnue-common/src/apps/checktype.py 2009-10-01 13:51:39 UTC (rev 9919) +++ trunk/gnue-common/src/apps/checktype.py 2009-10-02 09:47:54 UTC (rev 9920) @@ -1,30 +0,0 @@ -# GNU Enterprise Common Library - checktype support -# -# This file is part of GNU Enterprise. -# -# GNU Enterprise is free software; you can redistribute it -# and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation; either -# version 2, or (at your option) any later version. -# -# GNU Enterprise is distributed in the hope that it will be -# useful, but WITHOUT ANY WARRANTY; without even the implied -# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -# PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public -# License along with program; see the file COPYING. If not, -# write to the Free Software Foundation, Inc., 59 Temple Place -# - Suite 330, Boston, MA 02111-1307, USA. -# -# Copyright 2001-2009 Free Software Foundation -# -# $Id$ - -""" -Support for checking the type of variables. - -This module is *DEPRECATED*. Please use gnue.common.base.checktype instead. -""" - -from gnue.common.base.checktype import TypeError, checktype Deleted: trunk/gnue-common/src/base/checktype.py =================================================================== --- trunk/gnue-common/src/base/checktype.py 2009-10-01 13:51:39 UTC (rev 9919) +++ trunk/gnue-common/src/base/checktype.py 2009-10-02 09:47:54 UTC (rev 9920) @@ -1,186 +0,0 @@ -# GNU Enterprise Common Library - checktype support -# -# This file is part of GNU Enterprise. -# -# GNU Enterprise is free software; you can redistribute it -# and/or modify it under the terms of the GNU General Public -# License as published by the Free Software Foundation; either -# version 2, or (at your option) any later version. -# -# GNU Enterprise is distributed in the hope that it will be -# useful, but WITHOUT ANY WARRANTY; without even the implied -# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -# PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public -# License along with program; see the file COPYING. If not, -# write to the Free Software Foundation, Inc., 59 Temple Place -# - Suite 330, Boston, MA 02111-1307, USA. -# -# Copyright 2001-2009 Free Software Foundation -# -# $Id$ - -""" -Support for checking the type of variables. -""" - -import sys -import types - -from gnue.common.base import errors - -__all__ = ['TypeError', 'checktype'] - - -# ============================================================================= -# Exception definition -# ============================================================================= - -class TypeError(errors.SystemError): - """ - Raised when L{checktype} detects a wrong type. - - Do not raise this exception manually. - """ - def __init__(self, variable, expected): - - self.varname = '<?>' - for (key, val) in (sys._getframe(2)).f_locals.items(): - if variable is val: - self.varname = key - - self.expected = expected # Expected type of variable - - if isinstance(variable, types.InstanceType): - self.actual = variable.__class__ - else: - self.actual = type(variable) # Actual type of variable - - self.value = variable # Value of variable - - message = u_('"%(varname)s" is expected to be of %(expected)s but is ' - 'of %(actual)s and has value %(value)s') \ - % {'varname' : self.varname, - 'expected': self.__stringify(self.expected), - 'actual' : self.__stringify(self.actual), - 'value' : repr(self.value)} - errors.SystemError.__init__(self, message) - - - # ------------------------------------------------------------------------- - # Get a nice string for a given type - # ------------------------------------------------------------------------- - - def __stringify(self, atype): - - if isinstance(atype, list): - return ' / '.join([self.__stringify(ctp) for ctp in atype]) - - elif isinstance(atype, type): - return str(atype) - - elif isinstance(atype, types.ClassType): - return '<class %s>' % str(atype) - - else: - return '<type %s>' % str(atype) - - -# ----------------------------------------------------------------------------- -# Check type of a variable -# ----------------------------------------------------------------------------- - -def checktype(variable, validtype): - """ - Check a varaible (for example a parameter to a function) for a correct type. - This function is available as builtin function. - - @param variable: Variable to check. - @param validtype: Type, class, or a list of types and classes that are - valid. - @raise TypeError: The variable has a type not listed in the valid types. - """ - if isinstance(validtype, list): - for ctp in validtype: - if ctp is None: - if variable is None: - return - else: - if isinstance(variable, ctp): - return - else: - if isinstance(variable, validtype): - return - - raise TypeError, (variable, validtype) - - -# ----------------------------------------------------------------------------- -# Module initialization -# ----------------------------------------------------------------------------- - -import __builtin__ -__builtin__.__dict__['checktype'] = checktype - - -# ----------------------------------------------------------------------------- -# Self test code -# ----------------------------------------------------------------------------- - -if __name__ == '__main__': - - def mustfail(testvar, validtype): - """ - Test a variable agains a given type, assuming that the test fails - """ - try: - checktype(testvar, validtype) - - except TypeError, message: - print message - return - raise errors.Error("checking %s as %s hasn't failed!" % (repr(variable), - repr(validtype))) - - n = None - s = 'this is a string' - u = u'this is a unicode string' - i = 100 - f = 17.85 - class p: - pass - class c(p): - pass - o = c() - - print 'Single type, success ...' - checktype(n, types.NoneType) - checktype(s, str) - checktype(u, unicode) - checktype(i, int) - checktype(f, float) - checktype(c, types.ClassType) - checktype(o, types.InstanceType) - checktype(o, c) - checktype(o, p) - - print 'Multiple types, success ...' - checktype(n, [str, types.NoneType]) - checktype(s, [str, unicode]) - checktype(u, [str, unicode]) - checktype(o, [types.NoneType, c]) - - print 'Single type, failure ...' - mustfail(n, str) - mustfail(s, unicode) - mustfail(u, str) - mustfail(i, float) - mustfail(o, int) - mustfail(c, c) - - print 'Multiple types, failure ...' - mustfail(n, [str, unicode]) - mustfail(s, [int, float]) - - print 'All test passed.' Copied: trunk/gnue-common/src/lib/checktype.py (from rev 9918, trunk/gnue-common/src/base/checktype.py) =================================================================== --- trunk/gnue-common/src/lib/checktype.py (rev 0) +++ trunk/gnue-common/src/lib/checktype.py 2009-10-02 09:47:54 UTC (rev 9920) @@ -0,0 +1,183 @@ +# GNU Enterprise Common Library - Variable Type Checking +# +# Copyright 2001-2009 Free Software Foundation +# +# This file is part of GNU Enterprise +# +# GNU Enterprise is free software; you can redistribute it +# and/or modify it under the terms of the GNU General Public +# License as published by the Free Software Foundation; either +# version 2, or (at your option) any later version. +# +# GNU Enterprise is distributed in the hope that it will be +# useful, but WITHOUT ANY WARRANTY; without even the implied +# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public +# License along with program; see the file COPYING. If not, +# write to the Free Software Foundation, Inc., 59 Temple Place +# - Suite 330, Boston, MA 02111-1307, USA. +# +# $Id$ + +""" +Support for checking the type of variables. +""" + +import sys +import types + +__all__ = ['checktype'] + + +# ============================================================================= +# Type Check Routine +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Check type of a variable +# ----------------------------------------------------------------------------- + +def checktype(variable, valid_type): + """ + Check a varaible (for example a parameter to a function) for a correct type. + This function is available as builtin function. + + @param variable: Variable to check. + @param valid_type: Type, class, or a list of types and classes that are + valid. + @raise TypeError: The variable has a type not listed in the valid types. + """ + + # If type is ok, return without exception. + if isinstance(valid_type, list): + for t in valid_type: + if t is None: + if variable is None: + return + else: + if isinstance(variable, t): + return + else: + if isinstance(variable, valid_type): + return + + # The type is not ok, so raise the exception. + + # Find out variable name. + varname = '<?>' + for (key, val) in (sys._getframe(1)).f_locals.items(): + if variable is val: + varname = key + + # Find out variable type + if isinstance(variable, types.InstanceType): + actual_type = variable.__class__ + else: + actual_type = type(variable) + + raise TypeError('"%(varname)s" is expected to be of %(expected)s but is ' \ + 'of %(actual)s and has value %(value)s' % { + 'varname' : varname, + 'expected': __stringify(valid_type), + 'actual' : __stringify(actual_type), + 'value' : repr(variable)}) + + +# ----------------------------------------------------------------------------- +# Get a nice string for a given type +# ----------------------------------------------------------------------------- + +def __stringify(a_type): + + if isinstance(a_type, list): + return ' / '.join([__stringify(t) for t in a_type]) + + elif isinstance(a_type, type): + return str(a_type) + + elif isinstance(a_type, types.ClassType): + return '<class %s>' % str(a_type) + + else: + return '<type %s>' % str(a_type) + + +# ============================================================================= +# Module initialization +# ============================================================================= + +import __builtin__ +__builtin__.__dict__['checktype'] = checktype + + +# ============================================================================= +# Module self test code +# ============================================================================= + +if __name__ == '__main__': + + # ------------------------------------------------------------------------- + # Test of checktype function + # ------------------------------------------------------------------------- + + def __test_checktype(): + + def __mustfail(variable, valid_type): + try: + checktype(variable, valid_type) + except TypeError, message: + print message + return + raise TypeError("checking %s as %s hasn't failed!" % ( + repr(variable), repr(valid_type))) + + none_var = None + string_var = 'this is a string' + unicode_var = u'this is a unicode string' + integer_var = 100 + float_var = 17.85 + class ParentClass: + def __init__(self): + pass + class ChildClass(ParentClass): + pass + instance_var = ChildClass() + + print 'Single type, success ...' + checktype(none_var, types.NoneType) + checktype(string_var, str) + checktype(unicode_var, unicode) + checktype(integer_var, int) + checktype(float_var, float) + checktype(ChildClass, types.ClassType) + checktype(instance_var, types.InstanceType) + checktype(instance_var, ChildClass) + checktype(instance_var, ParentClass) + + print 'Multiple types, success ...' + checktype(none_var, [str, types.NoneType]) + checktype(string_var, [str, unicode]) + checktype(unicode_var, [str, unicode]) + checktype(instance_var, [types.NoneType, ChildClass]) + + print 'Single type, failure ...' + __mustfail(none_var, str) + __mustfail(string_var, unicode) + __mustfail(unicode_var, str) + __mustfail(integer_var, float) + __mustfail(instance_var, int) + __mustfail(ChildClass, ChildClass) + + print 'Multiple types, failure ...' + __mustfail(none_var, [str, unicode]) + __mustfail(string_var, [int, float]) + + print 'All test passed.' + + # ------------------------------------------------------------------------- + # Call all tests + # ------------------------------------------------------------------------- + + __test_checktype() Modified: trunk/gnue-common/tests/apps_checktype.py =================================================================== --- trunk/gnue-common/tests/apps_checktype.py 2009-10-01 13:51:39 UTC (rev 9919) +++ trunk/gnue-common/tests/apps_checktype.py 2009-10-02 09:47:54 UTC (rev 9920) @@ -29,7 +29,7 @@ import unittest from types import * -from gnue.common.apps.checktype import * +from gnue.common.lib.checktype import * class ChecktypeTestCase(unittest.TestCase): def setUp(self): _______________________________________________ commit-gnue mailing list commit-gnue@gnu.org http://lists.gnu.org/mailman/listinfo/commit-gnue