RE: Exception problem with module
Well I am not sure what advantage this has for the user, not my code as I don't advocate the import to begin with it, its fine spelled as it was from where it was... The advantage for the user is: /snip Hey Steven, Sorry for the late reply (travelling). My comment wasn't clear, I was ranting against the import of the exception in the second module, non the less how it was imported and not why it was not ok. Basically, it was no better than leaving it where it was, spelled as it was and requiring the user to import it from where it was defined. It turned out to be some faulty logic in the second module where the __setattr__ call was made that was preventing it from being set... jlc -- https://mail.python.org/mailman/listinfo/python-list
RE: Exception problem with module
I see that you've solved your immediate problem, but you shouldn't call __setattr__ directly. That should actually be written setattr(bar, 'a_new_name', MyError) But really, since bar is (apparently) a module, and it is *bar itself* setting the attribute, the better way is a_new_name = MyError or even from module.foo import MyError as a_new_name Well I am not sure what advantage this has for the user, not my code as I don't advocate the import to begin with it, its fine spelled as it was from where it was... I'll look back at this and see if that resolves the issue as it had manifested. jlc -- https://mail.python.org/mailman/listinfo/python-list
Re: Exception problem with module
On Wed, 14 May 2014 09:21:50 +, Joseph L. Casale wrote: I see that you've solved your immediate problem, but you shouldn't call __setattr__ directly. That should actually be written setattr(bar, 'a_new_name', MyError) But really, since bar is (apparently) a module, and it is *bar itself* setting the attribute, the better way is a_new_name = MyError or even from module.foo import MyError as a_new_name Well I am not sure what advantage this has for the user, not my code as I don't advocate the import to begin with it, its fine spelled as it was from where it was... The advantage for the user is: - it avoids module bar needing to get a reference to itself; - it avoids the distraction of unnecessarily calling a dunder method; - it is idiomatic Python code that should be instantly understandable by any even moderately experienced Python coder; - prevents the reader from puzzling over why the code does something so unusual (but why does he do this...?); - and avoids the inevitable anger and/or contempt when the reader works out that there is no good reason to write such unidiomatic code. One should code as if the next person who reads your program is an easily upset psychotic axe-murderer who knows where you live. You wouldn't condone writing y = x.__add__(1) instead of y = x + 1, you shouldn't condone writing module.__setattr__ directly either. I'll look back at this and see if that resolves the issue as it had manifested. I doubt it. Not unless module bar has done something weird, like define a function called __setattr__ that shadows the actual method and wraps the exception in another object. More likely, I think you'll find that the original MyError doesn't inherit from Exception. -- Steven D'Aprano http://import-that.dreamwidth.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Exception problem with module
On Wed, May 14, 2014 at 11:08 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: One should code as if the next person who reads your program is an easily upset psychotic axe-murderer who knows where you live. You wouldn't condone writing y = x.__add__(1) instead of y = x + 1, you shouldn't condone writing module.__setattr__ directly either. Oddly enough, I was referencing that first half earlier this evening :) There's a difference between x.__add__(1) and x + 1, though. The latter might end up calling (1).__radd__(x), which (obviously) the first won't. I can imagine there might be some use-case where you specifically DON'T want the reflected method to be silently called (maybe for introspection or debugging??). But it falls under code smell, the sort of thing where you absolutely MUST have a comment - like where I have a call to set_foreground(bg), because that could so easily be an error, yet in this case isn't. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Exception problem with module
I am working with a module that I am seeing some odd behavior. A module.foo builds a custom exception, module.foo.MyError, its done right afaict. Another module, module.bar imports this and calls bar.__setattr__('a_new_name', MyError). Now, not in all but in some cases when I catch a_new_name, my code raises a new exception: During handling of the above exception, another exception occurred: File C:/dir/test.py, line 12, in module except a_new_name as exc: TypeError: catching classes that do not inherit from BaseException is not allowed So, I wont suggest the assignment in bar added anything, nor would I do this, but its what I am working with. Why might this happen? MyError subclasses Exception and calls super passing back args. This has something to do with the assignment in bar, catching MyError obviously works. Any ideas? jlc -- https://mail.python.org/mailman/listinfo/python-list
Re: Exception problem with module
On Wed, May 14, 2014 at 2:59 AM, Joseph L. Casale jcas...@activenetwerx.com wrote: During handling of the above exception, another exception occurred: File C:/dir/test.py, line 12, in module except a_new_name as exc: TypeError: catching classes that do not inherit from BaseException is not allowed Best would be to print out what's in a_new_name to see if it really is what you think it is. If you think it is what you think it is, have a look at its __mro__ (method resolution order, it's an attribute of every class), to see what it's really inheriting. That should show you what's happening. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
RE: Exception problem with module
Best would be to print out what's in a_new_name to see if it really is what you think it is. If you think it is what you think it is, have a look at its __mro__ (method resolution order, it's an attribute of every class), to see what it's really inheriting. That should show you what's happening. Lol, In a sea of frustration with this, I cant believe I didn't do that. Problem solved. Thanks, jlc -- https://mail.python.org/mailman/listinfo/python-list
Re: Exception problem with module
On Tue, 13 May 2014 16:59:46 +, Joseph L. Casale wrote: I am working with a module that I am seeing some odd behavior. A module.foo builds a custom exception, module.foo.MyError, its done right afaict. Another module, module.bar imports this and calls bar.__setattr__('a_new_name', MyError). I see that you've solved your immediate problem, but you shouldn't call __setattr__ directly. That should actually be written setattr(bar, 'a_new_name', MyError) But really, since bar is (apparently) a module, and it is *bar itself* setting the attribute, the better way is a_new_name = MyError or even from module.foo import MyError as a_new_name -- Steven D'Aprano http://import-that.dreamwidth.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: exception problem
Charles Hixson wrote: On 06/25/2012 12:48 AM, Steven D'Aprano wrote: Catch any exception is almost certainly the wrong thing to do, almost always. This time it was the right thing No, it wasn't. If you hadn't caught it, Python would have printed it out for you, along with the full trace-back, giving you most if not all the information you needed to track down the bug. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 06/25/2012 12:48 AM, Steven D'Aprano wrote: On Sun, 24 Jun 2012 16:16:25 -0700, Charles Hixson wrote: But what I wanted was to catch any exception. Be careful of what you ask for, since you might get it. Catch any exception is almost certainly the wrong thing to do, almost always. The one good reason I've seen for a bare except is to wrap the top level of an application in order to redirect uncaught exceptions to something other than the console (such as a GUI error dialog box). And even then, you probably don't want to catch *all* exceptions, but only those that inherit from Exception: try: main() # run my application except Exception as err: display_error_dialog(err) # or log to a file, or something... This time it was the right thing, as I suspected that *SOME* exception was being thrown, but had no idea what one. The problem was I didn't know how to print the result when I caught the exception. This has since been cleared up, but first I found it on Google, and then I was told about it on the list. The documentation left me totally ... well, not uninformed, but confused. As I said it turned out to be a method call on an uninitialized variable, as I found out once I figured out how to list the result of catching the exception. Which is what I expected the documentation to show me how to do. The comments on the list have been vastly helpful, even if they still tend to assume that I know more than I do. (And even if some of them seem to be a bit ... off. E.g., suggesting that I generate the exception on purpose so I can find out what it is, when I started off with no idea as to WHAT the problem was.) What really annoys me is the way the documentation has worsened since python 2.5, but if you know what it is trying to tell you, then I guess you aren't bothered by undefined terms and lack of examples. I went away from programming in Python for a couple of years though, and I guess I missed the transition, or something. -- Charles Hixson -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Jun 28, 10:13 am, Charles Hixson charleshi...@earthlink.net wrote: On 06/25/2012 12:48 AM, Steven D'Aprano wrote: Catch any exception is almost certainly the wrong thing to do, almost always. This time it was the right thing, as I suspected that *SOME* exception was being thrown, but had no idea what one. The problem was I didn't know how to print the result when I caught the exception. I think you're still missing the point. If you _didn't_ have a bare try/except, the exception _would have been raised_ and the exception displayed. You _don't_ need an exception handler for exceptions to occur, they just occur. You _only_ need a handler when you want to, y'know, handle them. This has since been cleared up, but first I found it on Google, and then I was told about it on the list. The documentation left me totally ... well, not uninformed, but confused. As I said it turned out to be a method call on an uninitialized variable, as I found out once I figured out how to list the result of catching the exception. Which is what I expected the documentation to show me how to do. The documentation doesn't expect you to write code to block error reporting. If you had just removed the try/except, you would have seen the problem right away. What really annoys me is the way the documentation has worsened since python 2.5, but if you know what it is trying to tell you, then I guess you aren't bothered by undefined terms and lack of examples. I went away from programming in Python for a couple of years though, and I guess I missed the transition, or something. Can I suggest re-looking at the tutorial for errors exceptions? I really think you're making this a lot more difficult for yourself than it needs to be. http://docs.python.org/tutorial/errors.html -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Wed, 27 Jun 2012 17:13:00 -0700, Charles Hixson wrote: On 06/25/2012 12:48 AM, Steven D'Aprano wrote: On Sun, 24 Jun 2012 16:16:25 -0700, Charles Hixson wrote: But what I wanted was to catch any exception. Be careful of what you ask for, since you might get it. Catch any exception is almost certainly the wrong thing to do, almost always. The one good reason I've seen for a bare except is to wrap the top level of an application in order to redirect uncaught exceptions to something other than the console (such as a GUI error dialog box). And even then, you probably don't want to catch *all* exceptions, but only those that inherit from Exception: try: main() # run my application except Exception as err: display_error_dialog(err) # or log to a file, or something... This time it was the right thing, as I suspected that *SOME* exception was being thrown, but had no idea what one. The problem was I didn't know how to print the result when I caught the exception. [...] once I figured out how to list the result of catching the exception. If you had simply NOT caught it, the full traceback would have been printed automatically and you could have easily seen what exception was being raised, the error message, and where it was being raised from. This is exactly why you should not have used a bare except, or any except at all, but just let the uncaught exception print on its own. When trying to diagnose bugs, try...except is not your friend. Tracebacks are your friend. [...] What really annoys me is the way the documentation has worsened since python 2.5, but if you know what it is trying to tell you, then I guess you aren't bothered by undefined terms and lack of examples. I went away from programming in Python for a couple of years though, and I guess I missed the transition, or something. If you have concrete examples of where you think the documentation could be improved, please either raise an enhancement request or bug report: http://bugs.python.org/ or at least raise them here (and hope somebody else raised the bug report). Otherwise, there's nothing we can do about vague complaints. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
(You posted privately to me again; I hope you don't mind my responding on-list as this appears to have been merely oversight.) On Wed, Jun 27, 2012 at 5:25 AM, Charles Hixson charleshi...@earthlink.net wrote: Only thing is, this whole mess started when I was trying to trace down and expected error. (Which turned out to be self.chunkLine(... where self wasn't defined.) It was running without ANY error being displayed. Though as I look an outer loop is inclosed in a try:except:finally: It still has an unlabelled except, because I don't remember what exception is thrown when a file reads an unintelligible character (i.e., it isn't really a utf-8 file). Currently I've fixed all the files so that they're either utf-8 or just ASCII, so currently it isn't getting triggered, but it's still there. So that's probably the explanation. I think I'll fix that now. (I can, I guess, assume that any exception will be caught by except BasicException:) That's the problem, your blanket try/except. Don't do it! It blinds you. Same goes for catching Exception or BaseException. Catch what you really need to catch, and reserve catch-all statements for special cases where you don't have access to the console. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 26/06/2012 22:36, Chris Angelico wrote: (You posted privately to me again; I hope you don't mind my responding on-list as this appears to have been merely oversight.) On Wed, Jun 27, 2012 at 5:25 AM, Charles Hixson charleshi...@earthlink.net wrote: Only thing is, this whole mess started when I was trying to trace down and expected error. (Which turned out to be self.chunkLine(... where self wasn't defined.) It was running without ANY error being displayed. Though as I look an outer loop is inclosed in a try:except:finally: It still has an unlabelled except, because I don't remember what exception is thrown when a file reads an unintelligible character (i.e., it isn't really a utf-8 file). Currently I've fixed all the files so that they're either utf-8 or just ASCII, so currently it isn't getting triggered, but it's still there. So that's probably the explanation. I think I'll fix that now. (I can, I guess, assume that any exception will be caught by except BasicException:) That's the problem, your blanket try/except. Don't do it! It blinds you. Same goes for catching Exception or BaseException. Catch what you really need to catch, and reserve catch-all statements for special cases where you don't have access to the console. If you can't remember what exception is raised, just try raising it deliberately. Python _can_ be used interactively, after all. Even a short script to test it won't take you very long! -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 6/25/2012 12:27 AM, Charles Hixson wrote: The documentation section covering the except statement could stand to be a *LOT* clearer. I read the sections on the except statement and exception handlers several times and couldn't figure out was the as argument of the except statement was for. I agree that the tutorial doesn't explain the use of as very well, but it does cover that a bare except is not normally good to use: The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! I still don't really know what as means, except that if you use it, and you print out the target, you'll get some kind of informative message. as lets you refer to the exception object that was caught. I find this useful mainly for exceptions that have attributes (most built-in exceptions don't, but many user-defined exceptions do). A full traceback is much more useful for debugging than what a simple print(exc) will give. There are a few different ways to get traceback information without letting the exception simply propagate and terminate the program. You can get some simple information from sys.exc_info() (and you can feed the traceback object to a function in the traceback module), or you can log it with the logging.exception() function or the exception() method of a Logger from the same module. I recommend using logging. However, it's generally best to just let any unexpected exceptions propagate unless the program absolutely must continue, especially when debugging. -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Sun, 24 Jun 2012 18:45:45 -0400, Dave Angel wrote: Bare exceptions are the bane of programming; Using it is like trying to learn to drive while blindfolded. +1 QOTW I really wish bare exceptions were removed from Python 3. There's no point to try...except any longer, and it's just an attractive nuisance to beginners. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Sun, 24 Jun 2012 16:16:25 -0700, Charles Hixson wrote: But what I wanted was to catch any exception. Be careful of what you ask for, since you might get it. Catch any exception is almost certainly the wrong thing to do, almost always. The one good reason I've seen for a bare except is to wrap the top level of an application in order to redirect uncaught exceptions to something other than the console (such as a GUI error dialog box). And even then, you probably don't want to catch *all* exceptions, but only those that inherit from Exception: try: main() # run my application except Exception as err: display_error_dialog(err) # or log to a file, or something... -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Mon, 25 Jun 2012 09:51:15 +1000, Chris Angelico wrote: Mind you, I think every programmer should spend some time debugging blind. You're a cruel, cruel man. I suppose next you're going to say that every programmer should spend some time programming using Notepad as their only editor. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Mon, Jun 25, 2012 at 5:49 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Mon, 25 Jun 2012 09:51:15 +1000, Chris Angelico wrote: Mind you, I think every programmer should spend some time debugging blind. You're a cruel, cruel man. I suppose next you're going to say that every programmer should spend some time programming using Notepad as their only editor. No no, that's just *too* nasty. But there are times now and then when, perhaps, you're working remotely, and you have to figure out what's wrong without exception tracebacks. Sure, 95% of programmers will never be in that situation, but it's a good skill to have. And when that disaster _does_ strike and you're stuck with just a file uploader and a crashing script, you'll look awesome for being able to fix it in five minutes flat :) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 06/24/2012 11:23 PM, Andrew Berg wrote: On 6/25/2012 12:27 AM, Charles Hixson wrote: The documentation section covering the except statement could stand to be a *LOT* clearer. I read the sections on the except statement and exception handlers several times and couldn't figure out was the as argument of the except statement was for. I agree that the tutorial doesn't explain the use of as very well, but it does cover that a bare except is not normally good to use: The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! I still don't really know what as means, except that if you use it, and you print out the target, you'll get some kind of informative message. as lets you refer to the exception object that was caught. I find this useful mainly for exceptions that have attributes (most built-in exceptions don't, but many user-defined exceptions do). A full traceback is much more useful for debugging than what a simple print(exc) will give. There are a few different ways to get traceback information without letting the exception simply propagate and terminate the program. You can get some simple information from sys.exc_info() (and you can feed the traceback object to a function in the traceback module), or you can log it with the logging.exception() function or the exception() method of a Logger from the same module. I recommend using logging. However, it's generally best to just let any unexpected exceptions propagate unless the program absolutely must continue, especially when debugging. I read that that would happen, but print (sys.exc_info()[:2]) didn't even yield a blank line. It must have executed, because the print statement on the line before it executed, and there wasn't a loop or a jump (and also execution continued normally [the code still has bugs] afterward even if the finally isn't included). -- Charles Hixson -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Tue, Jun 26, 2012 at 1:14 AM, Charles Hixson charleshi...@earthlink.net wrote: I read that that would happen, but print (sys.exc_info()[:2]) didn't even yield a blank line. It must have executed, because the print statement on the line before it executed, and there wasn't a loop or a jump (and also execution continued normally [the code still has bugs] afterward even if the finally isn't included). Unless it threw an exception, such as NameError if you haven't imported sys. In that case, execution will continue through the 'finally' clause and then raise the exception (at least, I think that's how it goes - raising exceptions in exception handlers is not something I've made a study of). ChrisA -- http://mail.python.org/mailman/listinfo/python-list
exception problem
The code: print(pre-chunkLine) chunks=[] try: chunks=self.chunkLine (l) except: print(caught exception) print (sys.exc_info()[:2]) finally: print (at finally) print (chunks =) print (repr(chunks), ., end = :) produces this result: . . ., by pre-chunkLine caught exception at finally path 3... Any suggestions as to what's wrong with the code? FWIW, chunkLine begins: def chunkLine (self, line): print(chunkLine: ) print (line = , line) ifline == None: return[] assert(isinstance (line, str) ) -- Charles Hixson -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
Sorry, I left out: er$ python3 --version Python 3.2.3rc1 On 06/24/2012 03:26 PM, Charles Hixson wrote: The code: print(pre-chunkLine) chunks=[] try: chunks=self.chunkLine (l) except: print(caught exception) print (sys.exc_info()[:2]) finally: print (at finally) print (chunks =) print (repr(chunks), ., end = :) produces this result: . . ., by pre-chunkLine caught exception at finally path 3... Any suggestions as to what's wrong with the code? FWIW, chunkLine begins: def chunkLine (self, line): print(chunkLine: ) print (line = , line) ifline == None: return[] assert(isinstance (line, str) ) -- Charles Hixson -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Mon, Jun 25, 2012 at 8:26 AM, Charles Hixson charleshi...@earthlink.net wrote: The code: finally: print (at finally) print (chunks =) produces this result: path 3... Can you state more clearly the problem, please? I'm seeing output that can't have come from the code posted (for instance, immediately after the at finally, I'm expecting to see the chunks = line), and I'm not seeing any exception information, so I can't even hazard a guess as to what's throwing the exception. Presumably these are two methods in the same class, since you're calling it as self.chunkLine, but beyond that, it's hard to know. Take off the try/except and let your exception go to console, that's usually the easiest thing to deal with. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 24/06/2012 23:26, Charles Hixson wrote: The code: print(pre-chunkLine) chunks=[] try: chunks=self.chunkLine (l) except: print(caught exception) print (sys.exc_info()[:2]) finally: print (at finally) print (chunks =) print (repr(chunks), ., end = :) produces this result: . . ., by pre-chunkLine caught exception at finally path 3... Any suggestions as to what's wrong with the code? FWIW, chunkLine begins: def chunkLine (self, line): print(chunkLine: ) print (line = , line) ifline == None: return[] assert(isinstance (line, str) ) Don't use a bare except; it'll catch _any__exception. Catch only what you expect. For all I know, it could be that the name l doesn't exist. -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 06/24/2012 06:30 PM, Charles Hixson wrote: Sorry, I left out: er$ python3 --version Python 3.2.3rc1 On 06/24/2012 03:26 PM, Charles Hixson wrote: The code: print(pre-chunkLine) chunks=[] try: chunks=self.chunkLine (l) except: print(caught exception) print (sys.exc_info()[:2]) finally: print (at finally) print (chunks =) print (repr(chunks), ., end = :) produces this result: . . ., by pre-chunkLine caught exception at finally path 3... Any suggestions as to what's wrong with the code? FWIW, chunkLine begins: def chunkLine (self, line): print(chunkLine: ) print (line = , line) ifline == None: return[] assert(isinstance (line, str) ) On your except line, you forgot both the type of exception you're expecting and the variable to receive its value. So you're masking all errors, including a name error finding chunkline(). You don't include enough code to make the fragment executable, so I'd have to just guess. I'm guessing that chunkline() is not defined in the same class as that first method, whatever it was called. If this were my problem, probably first thing I'd try is to remove the try and catch, and see what it shows. Bare exceptions are the bane of programming; Using it is like trying to learn to drive while blindfolded. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 24/06/2012 23:36, Chris Angelico wrote: On Mon, Jun 25, 2012 at 8:26 AM, Charles Hixson charleshi...@earthlink.net wrote: The code: finally: print (at finally) print (chunks =) produces this result: path 3... Can you state more clearly the problem, please? I'm seeing output that can't have come from the code posted (for instance, immediately after the at finally, I'm expecting to see the chunks = line), and I'm not seeing any exception information, so I can't even hazard a guess as to what's throwing the exception. I'd expect the output of: print (sys.exc_info()[:2]) between these two lines: caught exception at finally That suggests to me that sys hasn't been imported and that's there's another exception somewhere that we're not seeing. Presumably these are two methods in the same class, since you're calling it as self.chunkLine, but beyond that, it's hard to know. Take off the try/except and let your exception go to console, that's usually the easiest thing to deal with. -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 06/24/2012 03:43 PM, MRAB wrote: On 24/06/2012 23:26, Charles Hixson wrote: The code: print(pre-chunkLine) chunks=[] try: chunks=self.chunkLine (l) except: print(caught exception) print (sys.exc_info()[:2]) finally: print (at finally) print (chunks =) print (repr(chunks), ., end = :) produces this result: . . ., by pre-chunkLine caught exception at finally path 3... Any suggestions as to what's wrong with the code? FWIW, chunkLine begins: def chunkLine (self, line): print(chunkLine: ) print (line = , line) ifline == None: return[] assert(isinstance (line, str) ) Don't use a bare except; it'll catch _any__exception. Catch only what you expect. For all I know, it could be that the name l doesn't exist. But what I wanted was to catch any exception. A problem was happening and I had no clue as to what it was. (It turned out to be self is not defined. A silly mistake, but a real one.) The odd thing was that if I ran it without the try block, I didn't get any exceptions at all. (Which I clearly should have, except that since self wasn't defined, I'd usually expect the interpreter to detect the error before trying to execute the code.) -- Charles Hixson -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On Mon, Jun 25, 2012 at 9:16 AM, Charles Hixson charleshi...@earthlink.net wrote: But what I wanted was to catch any exception. A problem was happening and I had no clue as to what it was. (It turned out to be self is not defined. A silly mistake, but a real one.) The odd thing was that if I ran it without the try block, I didn't get any exceptions at all. (Which I clearly should have, except that since self wasn't defined, I'd usually expect the interpreter to detect the error before trying to execute the code.) Python, not having any concept of declared variables, can't detect such errors prior to execution. The error isn't like in C where you're trying to use a variable that's not declared; the error is that, at run time, there's no global with the name self. That's why it's an exception, not a compile-time error. But the real question is: Why do you get no exception traceback if you remove the try/except? Is something else swallowing everything thrown? This is something that you will need to solve. (And it's a pretty annoying issue. We had the same thing here at work, though in Javascript not Python; a framework was swallowing exceptions, so all sorts of work was being done blindfolded. Legacy code is not fun. Life got a lot easier for us last Friday when I found and excised the offending try/catch.) Hunt around and see if exceptions are getting logged someplace other than your console - not uncommon if, for instance, you're running in a web server. This is not going to be the only time when you get an exception that could be massively helpful. Mind you, I think every programmer should spend some time debugging blind. It gives you such an appreciation for interactive debuggers. Plus, it's an exercise in making your problems reproducible, if you have to start your program over every time you add some more information to it :) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 06/24/2012 07:16 PM, Charles Hixson wrote: On 06/24/2012 03:43 PM, MRAB wrote: On 24/06/2012 23:26, Charles Hixson wrote: SNIP Don't use a bare except; it'll catch _any__exception. Catch only what you expect. For all I know, it could be that the name l doesn't exist. But what I wanted was to catch any exception. A problem was happening and I had no clue as to what it was. (It turned out to be self is not defined. A silly mistake, but a real one.) If you don't get anything else out of this thread, get this point. A bare except is exactly the opposite of what you want to debug an exception. It swallows all the information that python would have displayed for you. Four or five of us have made the same point, so please listen. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: exception problem
On 06/24/2012 03:43 PM, Charles Hixson wrote: On 06/24/2012 03:36 PM, Chris Angelico wrote: On Mon, Jun 25, 2012 at 8:26 AM, Charles Hixson charleshi...@earthlink.net wrote: The code: finally: print (at finally) print (chunks =) produces this result: path 3... Can you state more clearly the problem, please? I'm seeing output that can't have come from the code posted (for instance, immediately after the at finally, I'm expecting to see the chunks = line), and I'm not seeing any exception information, so I can't even hazard a guess as to what's throwing the exception. Presumably these are two methods in the same class, since you're calling it as self.chunkLine, but beyond that, it's hard to know. Take off the try/except and let your exception go to console, that's usually the easiest thing to deal with. Chris Angelico Sorry, but it *DID* come from the code posted. Which is why I was so confused. I finally tracked it down to self was not defined by altering the except section to read: except BaseException as ex: print(caught exception) print (ex) finally: print (at finally) The documentation section covering the except statement could stand to be a *LOT* clearer. I read the sections on the except statement and exception handlers several times and couldn't figure out was the as argument of the except statement was for. Target doesn't communicate much to me. The one I finally used as indicated above was modified from some code that I found through Google. I still don't really know what as means, except that if you use it, and you print out the target, you'll get some kind of informative message. (The one that I got said self was not defined .. that's a paraphrase. I can't remember the precise wording.) And that interpretation is based on what the result was, not on anything said in the documentation. IIRC, the Python2 documentation used code examples to indicate what was the right way to write an exception handler. I realize that Python3 is much different, but that approach was a very good one. -- Charles Hixson -- http://mail.python.org/mailman/listinfo/python-list
RE: exception problem
If you are not sure about the Exception, You can adopt a generic way of handling exception. try: except Exception,e: print str(e) -Shambhu -Original Message- From: MRAB [mailto:pyt...@mrabarnett.plus.com] Sent: 25/06/2012 4:14 AM To: python-list@python.org Subject: Re: exception problem On 24/06/2012 23:26, Charles Hixson wrote: The code: print(pre-chunkLine) chunks=[] try: chunks=self.chunkLine (l) except: print(caught exception) print (sys.exc_info()[:2]) finally: print (at finally) print (chunks =) print (repr(chunks), ., end = :) produces this result: . . ., by pre-chunkLine caught exception at finally path 3... Any suggestions as to what's wrong with the code? FWIW, chunkLine begins: def chunkLine (self, line): print(chunkLine: ) print (line = , line) ifline == None: return[] assert(isinstance (line, str) ) Don't use a bare except; it'll catch _any__exception. Catch only what you expect. For all I know, it could be that the name l doesn't exist. -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclass conflict TypeError exception: problem demonstration script
Barak, Ron ron.ba...@lsi.com writes: However, when line 7 is in effect (with line 8 commented out), viz.: $ cat -n metaclass_test01.py | head 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste): If this is the actual source you're running, then CopyAndPaste is a module, not a type, and that causes the conflict. Use CopyAndPaste.CopyAndPaste, or change the import line to read from CopyAndPaste import CopyAndPaste. Or, even better, adhere to recommendations laid down in PEP 8 and you'll avoid confusion between module and class names. -- http://mail.python.org/mailman/listinfo/python-list
Metaclass conflict TypeError exception: problem demonstration script
Hi Guys, Thanks to Michele, Chris, Hrvoje et. al. who helped me trying to resolve the metaclass exception when a class has two parents problem. This post tries to unify all the metaclasses exception threads, in an attempt to reach a solution. I've created a short demo script (metaclass_test01.py) that demonstrate the problem. Listings of metaclass_test01.py and CopyAndPaste are below and attached. Note: When line 8 in metaclass_test01.py is in effect (with line 7 commented out), the script runs normally. However, when line 7 is in effect (with line 8 commented out), viz.: $ cat -n metaclass_test01.py | head 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste): 8 #class ListControl(wx.Frame): 9 def __init__(self, parent, id, title, list, max_list_width): 10 wx.Frame.__init__(self,parent,id,title,size=(-1,-1), style=wx.DEFAULT_FRAME_STYLE) I get the metaclass conflict exception: $ python metaclass_test01.py Traceback (most recent call last): File metaclass_test01.py, line 7, in module class ListControl(wx.Frame, CopyAndPaste): TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I hope that now the problem is demonstrated more clearly, and the gurus out there could point me in the right direction towards a solution. Bye, Ron. $ cat -n metaclass_test01.py 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 #class ListControl(wx.Frame, CopyAndPaste): 8 class ListControl(wx.Frame): 9 def __init__(self, parent, id, title, list, max_list_width): 10 wx.Frame.__init__(self,parent,id,title,size=(-1,-1), style=wx.DEFAULT_FRAME_STYLE) 11 self.list = list 12 self.list_ctrl = wx.ListCtrl(self, -1, style=wx.LC_REPORT| wx.LC_NO_HEADER) 13 self.list_ctrl.InsertColumn(0, title) 14 for i,line_ in enumerate(list): 15 self.list_ctrl.InsertStringItem(i, line_) 16 self.list_ctrl.SetColumnWidth(0, max_list_width) 17 18 self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.list_ctrl) 19 20 self.Raise() 21 self.Show(True) 22 23 def OnItemSelected(self, evt): 24 item = evt.GetText() 25 max_list_width = 10 * len(item) 26 ListControl(self, -1, item, item, max_list_width) 27 28 if __name__ == __main__: 29 list = [ First Line, Second Line, Third Line] 30 app = wx.App(redirect=False) 31 max_list_width = 6 * max([len(x) for x in list]) 32 ListControl(None, -1, Parent Window, list, max_list_width) 33 app.MainLoop() $ cat -n CopyAndPaste.py 1 #!/usr/bin/env python 2 3 import wx 4 5 class CopyAndPaste(object): 6 7 def __init__(self): 8 pass 9 10 def set_copy_and_paste(self): 11 12 Setting clipboard copy-and-pasting (only copying from the application to the 13 clipboard is supported). 14 The menu menu is hidden, and is only there to facilitate the acceleration table. 15 Both CTRL-C and CTRL-Ins are supported. 16 17 menu = wx.Menu() 18 copy_ = menu.Append(-1, Copy\tCtrl-Ins) # Copy with accelerator 19 minimize_ = menu.Append(-1, Minimize) # 20 close_ = menu.Append(-1, Close window\tCtrl-W) # Close window 21 exit_ = menu.Append(-1, Exit application\tCtrl-X) # Close window 22 23 self.Bind(wx.EVT_MENU, self.on_copy, copy_) 24 self.Bind(wx.EVT_MENU, self.on_minimize, minimize_) 25 self.Bind(wx.EVT_MENU, self.on_close, close_) 26 self.Bind(wx.EVT_MENU, self.on_exit, exit_) 27 28 menuBar = wx.MenuBar() 29 self.SetMenuBar(menuBar) 30 31 acceltbl = wx.AcceleratorTable( [ 32 (wx.ACCEL_CTRL, ord('C'), copy_.GetId()), 33 (wx.ACCEL_CTRL, ord('W'), close_.GetId()), 34 (wx.ACCEL_CTRL, ord('X'), exit_.GetId()), 35 (wx.ACCEL_CTRL, ord('Q'), exit_.GetId()), 36 (wx.ACCEL_CTRL, wx.WXK_INSERT, copy_.GetId()), 37 (wx.ACCEL_CTRL, wx.WXK_NUMPAD_INSERT, copy_.GetId()), 38 ]) 39 self.SetAcceleratorTable(acceltbl) 40 41 # Setting popup menu 42 43 self.popupmenu = menu 44 self.Bind(wx.EVT_CONTEXT_MENU, self.on_show_popup) 45 46 def on_show_popup(self, evt): 47
Re: Metaclass conflict TypeError exception: problem demonstration script
$ cat -n metaclass_test01.py | head 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste): 8 #class ListControl(wx.Frame): 9 def __init__(self, parent, id, title, list, max_list_width): 10 wx.Frame.__init__(self,parent,id,title,size=(-1,-1), style=wx.DEFAULT_FRAME_STYLE) I get the metaclass conflict exception: You're trying to use a module as a base class. Don't do that; it doesn't work. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclass conflict TypeError exception: problem demonstration script
En Mon, 23 Feb 2009 07:32:52 -0200, Barak, Ron ron.ba...@lsi.com escribió: $ cat -n metaclass_test01.py | head 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste): 8 #class ListControl(wx.Frame): 9 def __init__(self, parent, id, title, list, max_list_width): 10 wx.Frame.__init__(self,parent,id,title,size=(-1,-1), style=wx.DEFAULT_FRAME_STYLE) I get the metaclass conflict exception: $ python metaclass_test01.py Traceback (most recent call last): File metaclass_test01.py, line 7, in module class ListControl(wx.Frame, CopyAndPaste): TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I hope that now the problem is demonstrated more clearly, and the gurus out there could point me in the right direction towards a solution. You want the CopyAndPaste *class*, not the *module*! -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Solved: Metaclass conflict TypeError exception: problem demonstration script
Hi, -Original Message- From: Tim Golden [mailto:m...@timgolden.me.uk] Sent: Monday, February 23, 2009 11:37 Cc: python-list@python.org; wxpython-us...@lists.wxwidgets.org Subject: Re: Metaclass conflict TypeError exception: problem demonstration script $ cat -n metaclass_test01.py | head 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste): 8 #class ListControl(wx.Frame): 9 def __init__(self, parent, id, title, list, max_list_width): 10 wx.Frame.__init__(self,parent,id,title,size=(-1,-1), style=wx.DEFAULT_FRAME_STYLE) I get the metaclass conflict exception: You're trying to use a module as a base class. Don't do that; it doesn't work. TJG That's it. Once I changed my class header to: $ cat -n metaclass_test01.py 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste.CopyAndPaste): I'm getting no more Metaclass conflict TypeError exceptions :-) (a clear case of The Devil Is In The ...) Thanks so much, Ron. -- http://mail.python.org/mailman/listinfo/python-list
Re: Solved: Metaclass conflict TypeError exception: problem demonstration script
Barak, Ron wrote: That's it. Once I changed my class header to: $ cat -n metaclass_test01.py 1 #!/usr/bin/env python 2 3 import sys 4 import wx 5 import CopyAndPaste 6 7 class ListControl(wx.Frame, CopyAndPaste.CopyAndPaste): I'm getting no more Metaclass conflict TypeError exceptions :-) (a clear case of The Devil Is In The ...) Glad we could help. Also a good indication of how important it is to produce real code which really fails in the real way! Sometimes you can look at it yourself even before you post and see the problem. :) TJG -- http://mail.python.org/mailman/listinfo/python-list