| 1 |
|
|---|
| 2 |
|
|---|
| 3 |
"""Functions to verify an argument's type |
|---|
| 4 |
|
|---|
| 5 |
|
|---|
| 6 |
|
|---|
| 7 |
|
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
|
|---|
| 11 |
|
|---|
| 12 |
|
|---|
| 13 |
|
|---|
| 14 |
__author__ = "Mike Orr <iron@mso.oz.net>" |
|---|
| 15 |
__revision__ = "$Revision: 1.4 $"[11:-2] |
|---|
| 16 |
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 19 |
|
|---|
| 20 |
import types |
|---|
| 21 |
|
|---|
| 22 |
|
|---|
| 23 |
|
|---|
| 24 |
|
|---|
| 25 |
def _errmsg(argname, ltd, errmsgExtra=''): |
|---|
| 26 |
"""Construct an error message. |
|---|
| 27 |
|
|---|
| 28 |
argname, string, the argument name. |
|---|
| 29 |
ltd, string, description of the legal types. |
|---|
| 30 |
errmsgExtra, string, text to append to error mssage. |
|---|
| 31 |
Returns: string, the error message. |
|---|
| 32 |
""" |
|---|
| 33 |
if errmsgExtra: |
|---|
| 34 |
errmsgExtra = '\n' + errmsgExtra |
|---|
| 35 |
return "arg '%s' must be %s%s" % (argname, ltd, errmsgExtra) |
|---|
| 36 |
|
|---|
| 37 |
|
|---|
| 38 |
|
|---|
| 39 |
|
|---|
| 40 |
|
|---|
| 41 |
def VerifyType(arg, argname, legalTypes, ltd, errmsgExtra=''): |
|---|
| 42 |
"""Verify the type of an argument. |
|---|
| 43 |
|
|---|
| 44 |
arg, any, the argument. |
|---|
| 45 |
argname, string, name of the argument. |
|---|
| 46 |
legalTypes, list of type objects, the allowed types. |
|---|
| 47 |
ltd, string, description of legal types (for error message). |
|---|
| 48 |
errmsgExtra, string, text to append to error message. |
|---|
| 49 |
Returns: None. |
|---|
| 50 |
Exceptions: TypeError if 'arg' is the wrong type. |
|---|
| 51 |
""" |
|---|
| 52 |
if type(arg) not in legalTypes: |
|---|
| 53 |
m = _errmsg(argname, ltd, errmsgExtra) |
|---|
| 54 |
raise TypeError(m) |
|---|
| 55 |
|
|---|
| 56 |
|
|---|
| 57 |
def VerifyTypeClass(arg, argname, legalTypes, ltd, klass, errmsgExtra=''): |
|---|
| 58 |
"""Same, but if it's a class, verify it's a subclass of the right class. |
|---|
| 59 |
|
|---|
| 60 |
arg, any, the argument. |
|---|
| 61 |
argname, string, name of the argument. |
|---|
| 62 |
legalTypes, list of type objects, the allowed types. |
|---|
| 63 |
ltd, string, description of legal types (for error message). |
|---|
| 64 |
klass, class, the parent class. |
|---|
| 65 |
errmsgExtra, string, text to append to the error message. |
|---|
| 66 |
Returns: None. |
|---|
| 67 |
Exceptions: TypeError if 'arg' is the wrong type. |
|---|
| 68 |
""" |
|---|
| 69 |
VerifyType(arg, argname, legalTypes, ltd, errmsgExtra) |
|---|
| 70 |
|
|---|
| 71 |
if type(arg) == types.ClassType and not issubclass(arg, klass): |
|---|
| 72 |
|
|---|
| 73 |
m = _errmsg(argname, ltd, errmsgExtra) |
|---|
| 74 |
raise TypeError(m) |
|---|
| 75 |
|
|---|
| 76 |
|
|---|
| 77 |
|
|---|
| 78 |
|
|---|
| 79 |
|
|---|
| 80 |
|
|---|
| 81 |
|
|---|
| 82 |
|
|---|
| 83 |
|
|---|