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.Type Error:
.. # extra = string of function/method +
.. # parameters inspect.getargs pec(function or method)
.. import traceback
.. tblines = traceback.forma t_exception(typ e, value, tb)
.. tblines.append( extra)
.. print "".join( map(str, tblines) )
.. sys.exit(1)
..
.. sys.excepthook = excepthook
inspect.getargs pec 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_va lue)
extra = extra[:extra.find("() ")]
Thank you,
Bearophile 3 1123
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.prin t_exc()
- print "Locals by frame, innermost last"
- for frame in stack:
- print
- print "Frame %s in %s at line %s" % \
- (frame.f_code.c o_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__.__n ame__, 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__.Spa m instance at 0xb7e0720c>
- __doc__ = None
-Frame eggs in ./test2.py at line 8
- self = <__main__.Spa m instance at 0xb7e0720c>
-Error 'xxx'
>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
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 ZeroDivisionErr or 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__.__n ame__, 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_originato r = stack[0]
-
- (obj, instance) = error_originato r.f_locals.item s()[0]
-
- self._str = 'class instance: %s, method: %s raises %s' % \
- (instance, \
- error_originato r.f_code.co_nam e, \
- arg)
-
- def __repr__(self):
- return repr(self._str)
Now the output is:
Error 'class instance: <__main__.Spa m instance at 0xb7e0444c>, method:
eggs raises ZeroDivisionErr or: 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 rlen;
int code;
short int reserved;
char indexName;
|
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 code or other people's code
you have come across would be appreciated. I am also trying to identify the
likelihood nad frequency of scenarios where smart pointer solutions would
not be appropriate, i.e. for some reason such as performance or...
|
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:
_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)" whenever I run my code below.
program works fine after I bypass the msg.
any ideas? thx a lot.
|
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 ???
Thank you,
Maadhuu.
//Smart.h
#ifndef _SMART_H
|
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 like this:
function onload() {
<% if (some_condition) { %>
do_some_javascript();
<% } %>
| |
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, but I just don't know.
I don't like them because I don't trust them. I use new and delete on pure
pointers instead.
Do you use smart pointers?
|
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 the advantages of smart
pointers endlessly (which are currently used in all our C++ software; we
use the Boost smart pointers) as I'm seriously concerned that there is a
shift to raw pointers. We are not developing system software but rather...
|
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 implement this. I've done some VB6
programming and dabbled in VS.Net.
Can someone share some pointers in how I could implement the following?
Basically, you drag a file to the "smart" folder and, depending on the type
of file and settings for that...
|
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 class ContactCollection;
|
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):
//------------------------------------------------------------------
template<typename Data_t>
class SmartPointer
{
Data_t* data;
void(*deleterFunc)(Data_t*);
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
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 we have to send another system
| |