473,507 Members | 3,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Smart help again

Hello, here I extend the idea of the smart help I've discussed
recently.
When I receive an error like:

TypeError: fun() takes exactly 2 arguments (1 given)

I'd also like to see that method/function parameters (or the first line
of its docstring).
From a discussion with gentle programmers in another newsgroup, I've

see that this problem can probably be solved with something like:

.. import sys, exceptions, difflib, inspect
..
.. def excepthook(type, value, tb):
.. extra = ""
.. if sys.last_type == exceptions.TypeError:
.. # extra = string of function/method +
.. # parameters inspect.getargspec(function or method)
.. import traceback
.. tblines = traceback.format_exception(type, value, tb)
.. tblines.append(extra)
.. print "".join( map(str, tblines) )
.. sys.exit(1)
..
.. sys.excepthook = excepthook
inspect.getargspec is useful, but how can I find there the class+method
or (function name) of the raised error? I can find the function name
with something like this, but it doesn't look like a nice solution, and
it cannot be used to find the class of the method:

extra = str(sys.last_value)
extra = extra[:extra.find("()")]

Thank you,
Bearophile

Jul 18 '05 #1
3 1117
You can create your own Exception class, based on thisrecipe:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52215, it will
look like

-import sys, traceback
-
-class Error:
- def __init__(self, arg):
- self._arg = arg
- tb = sys.exc_info()[2]
- while 1:
- if not tb.tb_next:
- break
- tb = tb.tb_next
- stack = []
- f = tb.tb_frame
- while f:
- stack.append(f)
- f = f.f_back
- stack.reverse()
- #traceback.print_exc()
- print "Locals by frame, innermost last"
- for frame in stack:
- print
- print "Frame %s in %s at line %s" % \
- (frame.f_code.co_name, frame.f_code.co_filename,
-frame.f_lineno)
- for key, value in frame.f_locals.items():
- print "\t%20s = " % key,
- #We have to be careful not to cause a new error in our
-error
- #printer! Calling str() on an unknown object could
cause -an
- #error we don't want.
- try:
- print value
- except:
- print "<ERROR WHILE PRINTING VALUE>"-
-
- def __repr__(self):
- return repr(self._arg)
-

suppose this class is in a module named test.py, then your code can be
like:

-#!/usr/bin/env python
-import test, sys

-try:
- try:
- class Spam:
- def eggs(self):
- return 1/0
- foo = Spam()
- foo.eggs()
- except:
- raise test.Error('xxx')
-except test.Error, e:
- print >> sys.stderr, e.__class__.__name__, e
The output will be:
-Locals by frame, innermost last
-
-Frame ? in ./test2.py at line 12
- Spam = __main__.Spam
- __builtins__ = <module '__builtin__' (built-in)>
- __file__ = ./test2.py
- sys = <module 'sys' (built-in)>
- test = <module 'test' from
'/home/martin/test.pyc'>
- __name__ = __main__
- foo = <__main__.Spam instance at 0xb7e0720c>
- __doc__ = None

-Frame eggs in ./test2.py at line 8
- self = <__main__.Spam instance at 0xb7e0720c>
-Error 'xxx'

Jul 18 '05 #2
>You can create your own Exception class, based on this recipe:<

Thank you for your answer, the recipe you have suggested gives a very
big output, but it doesn't contain what I've asked for... :-) I was
asking to see that faulty method/function parameters (or the first line
of its docstring).
Probably the use of sys.excepthook is better, because you don't need
that
except: raise test.Error('xxx')
I've studied that solution of yours, and I think I still have to learn
many things about Python :-)

Bye, thank you,
Bearophile

Jul 18 '05 #3
I hope a rewrite makes it a bit more clear for you.

The test module is defined below, it contains a simplified Error
object, it resemble the one I use a lot in my own scripting. The test
file generates an error ( A ZeroDivisionError in method eggs of class
Spam).

-#!/usr/bin/env python

-import test, sys
-
-try:
- try:
- class Spam:
- def eggs(self):
- return 1/0
- foo = Spam()
- foo.eggs()
- except Exception, e:
- raise test.Error('%s: %s' % (e.__class__.__name__, e))
-except test.Error, e:
- print >> sys.stderr, e.__class__.__name__, e

The Error class takes the last exception, and tries to find the
originating method of that exception, by unwinding the stacktrace
-import sys, traceback
-class Error:
- def __init__(self, arg):
- tb = sys.exc_info()[2]
- while 1:
- if not tb.tb_next:
- break
- tb = tb.tb_next
- stack = []
- f = tb.tb_frame
- while f:
- stack.append(f)
- f = f.f_back
-
- error_originator = stack[0]
-
- (obj, instance) = error_originator.f_locals.items()[0]
-
- self._str = 'class instance: %s, method: %s raises %s' % \
- (instance, \
- error_originator.f_code.co_name, \
- arg)
-
- def __repr__(self):
- return repr(self._str)

Now the output is:
Error 'class instance: <__main__.Spam instance at 0xb7e0444c>, method:
eggs raises ZeroDivisionError: integer division or modulo by zero'

Now you see the class and methos where the exception was raised,
although I admit that it is quite complicated with all the exception
handling

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2242
by: lokb | last post by:
Hi, I have a structure which and defined a smart pointer to the structure. /* Structure of Begin Document Index Record */ typedef struct BDI_Struct{ unsigned char rname; unsigned short int...
9
2124
by: christopher diggins | last post by:
I would like to survey how widespread the usage of smart pointers in C++ code is today. Any anecdotal experience about the frequency of usage of smart pointer for dynamic allocation in your own...
4
4286
by: A_StClaire_ | last post by:
I read a section of my text on smart "counting" pointers and found it confusing so I decided to get hands-on. however I'm getting "Debug Assertion Failed... Expression:...
3
2289
by: maadhuu | last post by:
Hello, I have tried this smart pointer implementation, but it is not working and I am not able to figure out why .......Also, can you please suggest more effective way/s of doing the same ???...
3
1506
by: ajfish | last post by:
Hi, I have a web form with smart navigation turned on. the html has an onload event which calls a javascript function and the contents of this function are dynamically generated on the server...
92
5001
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers,...
54
11908
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining...
5
2879
by: Noozer | last post by:
I'm looking for a "smart folder" program to run on my Windows XP machine. I'm not having any luck finding it and think the logic behind the program is pretty simple, but I'm not sure how I'd...
1
2063
by: mosfet | last post by:
Hi, I am trying to modify existing code to use smart pointers and I get some issues with virtual methods : class Folder : public Object { public: friend class PimItemCollection; friend...
50
4429
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): ...
0
7110
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7314
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7372
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7482
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3191
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1540
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.