[3] | 1 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) |
---|
| 2 | # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php |
---|
| 3 | """ |
---|
| 4 | Fixes the vague error message that you get when calling a function |
---|
| 5 | with the wrong arguments. |
---|
| 6 | """ |
---|
| 7 | import inspect |
---|
| 8 | import sys |
---|
| 9 | |
---|
| 10 | def fix_type_error(exc_info, callable, varargs, kwargs): |
---|
| 11 | """ |
---|
| 12 | Given an exception, this will test if the exception was due to a |
---|
| 13 | signature error, and annotate the error with better information if |
---|
| 14 | so. |
---|
| 15 | |
---|
| 16 | Usage:: |
---|
| 17 | |
---|
| 18 | try: |
---|
| 19 | val = callable(*args, **kw) |
---|
| 20 | except TypeError: |
---|
| 21 | exc_info = fix_type_error(None, callable, args, kw) |
---|
| 22 | raise exc_info[0], exc_info[1], exc_info[2] |
---|
| 23 | """ |
---|
| 24 | if exc_info is None: |
---|
| 25 | exc_info = sys.exc_info() |
---|
| 26 | if (exc_info[0] != TypeError |
---|
| 27 | or str(exc_info[1]).find('arguments') == -1 |
---|
| 28 | or getattr(exc_info[1], '_type_error_fixed', False)): |
---|
| 29 | return exc_info |
---|
| 30 | exc_info[1]._type_error_fixed = True |
---|
| 31 | import inspect |
---|
| 32 | argspec = inspect.formatargspec(*inspect.getargspec(callable)) |
---|
| 33 | args = ', '.join(map(_short_repr, varargs)) |
---|
| 34 | if kwargs and args: |
---|
| 35 | args += ', ' |
---|
| 36 | if kwargs: |
---|
| 37 | kwargs = kwargs.items() |
---|
| 38 | kwargs.sort() |
---|
| 39 | args += ', '.join(['%s=...' % n for n, v in kwargs]) |
---|
| 40 | gotspec = '(%s)' % args |
---|
| 41 | msg = '%s; got %s, wanted %s' % (exc_info[1], gotspec, argspec) |
---|
| 42 | exc_info[1].args = (msg,) |
---|
| 43 | return exc_info |
---|
| 44 | |
---|
| 45 | def _short_repr(v): |
---|
| 46 | v = repr(v) |
---|
| 47 | if len(v) > 12: |
---|
| 48 | v = v[:8]+'...'+v[-4:] |
---|
| 49 | return v |
---|
| 50 | |
---|
| 51 | def fix_call(callable, *args, **kw): |
---|
| 52 | """ |
---|
| 53 | Call ``callable(*args, **kw)`` fixing any type errors that come |
---|
| 54 | out. |
---|
| 55 | """ |
---|
| 56 | try: |
---|
| 57 | val = callable(*args, **kw) |
---|
| 58 | except TypeError: |
---|
| 59 | exc_info = fix_type_error(None, callable, args, kw) |
---|
| 60 | raise exc_info[0], exc_info[1], exc_info[2] |
---|
| 61 | return val |
---|