Exception or not


Suppose you have some HTML forms which you would like to validate. Every field can have different errors. For example, this are the forms: username password etc And you want to validate them with some class. Is this good pattern: ...
Posted On: Sunday 25th of November 2012 11:03:13 PM Total Views:  55
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




How do I unit-test a specific case of a home-rolled exception ?

""" I'm a bit new to both home-made exceptions and unit tests, so sorry if I'm just being stupid or doing it totally wrong. I have an exception class, and I want to check that a particular instance of it has been raised; or more accurately that one is raised that is equal to an instance I specify. In the example below, I can check that a 'LongRationalError' is raised, but I want to check that it is specifically a 'LongrationalError('1') or a 'LongRationalError('2') How do I do that +++++++++++++++++++++++++++++++++ The critical line is: self.assertRaises(LongRationalError, LongRational, 1, "7") and it doesn't work if i put: self.assertRaises(LongRationalError('2'), LongRational, 1, "7") +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ import unittest class LongRationalError(Exception): Message={} Message['1']="numerator must be an integer" Message['2']="denominator must be an integer" def __init__(self, code): self.code = str(code) def __str__(self): k = self.code if k in self.Message.keys(): v = self.Message[k] else: v = '...no description provided' return "Long Rational error #%s: %s" % (k,v) class LongRational(): import types allowed = [types.IntType,types.LongType] def __init__(self,a,b): if type(a) not in self.allowed: raise LongRationalError("1") if type(b) not in self.allowed: raise LongRationalError("2") if b == 0: raise ValueError("supplied denominator must be non-zero") if a == 0: b = 1 self.numerator=long(a) self.denominator=long(b) class TestLongRationals(unittest.TestCase): def test_init(self): # if the supplied denominator == zero, we should get a ValueError # if the supplied numerator or denominator is anything but an integer or a # long we should # raise a LongRational exception from types import LongType e = LongRational(123,456) self.assertRaises(ValueError, LongRational, 1, 0) self.assertRaises(LongRationalError, LongRational, 1.0, 2) self.assertRaises(LongRationalError, LongRational, 3, 4.0) self.assertRaises(LongRationalError, LongRational, 1, "7") self.assertEquals(e.numerator,123) self.assertEquals(e.denominator,456L) self.assertEquals(type(e.numerator),LongType) self.assertEquals(type(e.denominator),LongType) # special case: denominator of zero rational forced to unity. self.assertEquals(LongRational(0,24).denominator, 1L) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestLongRationals) unittest.TextTestRunner(verbosity=2).run(suite)
VIEWS ON THIS POST

81

Posted on:

Wednesday 7th November 2012
View Replies!

Unhandled exceptions checking

Does somebody know existent tool for checking unhandled exceptions Like in Java when method throws exception but in code using this method, try...catch is missed. May be something like PyChecker -- /Pavel
VIEWS ON THIS POST

85

Posted on:

Wednesday 7th November 2012
View Replies!

Re: Inconsistency in retrieving exceptions via sys module

En Mon, 12 May 2008 13:47:45 -0300, Raj Bandyopadhyay escribi: > I am writing some C code which sets and retrieves a Python exception. I > set the exception using PyErr_SetString(), and retrieve it in 2 ways: 1) > using PyErr_Occurred() and 2) Using sys.exc_type. However, I get two > different results and am very puzzled by this apparent inconsistency. > Could anyone please clarify what I'm missing I need both to work > consistently for my application. The sys.exc_* variables are just for backwards compatibility, don't use them; use sys.exc_info() in Python code and PyErr_Occurred (and the other PyErr... functions) in C. (Note that even PyErr_Occurred is not so common in C code, as most functions have some way to say "there was an error"; by example, functions that return a PyObject* mark an error returning NULL). The sys.exc_* variables are set only at the end of each Python bytecode instruction (see ceval.c) -- Gabriel Genellina
VIEWS ON THIS POST

131

Posted on:

Wednesday 7th November 2012
View Replies!

Raising exception on STDIN read

I would like to raise an exception any time a subprocess tries to read from STDIN: latexprocess = subprocess.Popen( \ 'pdflatex' + " " \ + 'test' + " 2>&1", \ shell=True, \ cwd=os.getcwd(), \ env=os.environ, \ stdin=StdinCatcher() # any ideas here ) An exception should be raised whenever the pdflatex process reads from STDIN... and I have no idea how to do it. Any suggestions
VIEWS ON THIS POST

104

Posted on:

Wednesday 7th November 2012
View Replies!

Pyrex bitten by the exception bug

I am running into the (apparently) well-known issue with pyrex that trying to raise an exception using python2.5 and pyrex will lead to a TypeError, as "TypeError: exceptions must be strings, classes, or instances, not exceptions.ImportError" Is there a fixc for this issue best regards, Paul Sijben
VIEWS ON THIS POST

92

Posted on:

Wednesday 7th November 2012
View Replies!

Re: replacing built-in exception types

Similarly I would ask then, why would you want to set class attributes on the built-in Exception classes On Dec 11, 2007, at 9:29 PM, Nishkar Grover wrote: > > I'm trying to replace the built-in base exception class with a > subclass of itself in python 2.5 because we can no longer add > attributes to that... > > % python2.4 -c 'import exceptions; exceptions.Exception.bar = 1234' > > % python2.5 -c 'import exceptions; exceptions.Exception.bar = 1234' > Traceback (most recent call last): > File "", line 1, in > TypeError: can't set attributes of built-in/extension type > 'exceptions.Exception' > > % python2.5 -c 'import exceptions; exceptions.BaseException.bar = > 1234' > Traceback (most recent call last): > File "", line 1, in > TypeError: can't set attributes of built-in/extension type > 'exceptions.BaseException' > > I already have a way to programatically construct the hierarchy of > subclasses, so for example, my subclass of OSError is a subclass of > the built-in OSError and a subclass of my subclass of > EnvironmentError. The only thing left to do is find a way to > replace the built-in exception types with my custom ones. > > - Nishkar > > > Calvin Spealman wrote: >> Why would you do this How to do it, if its even possible, is far >> less >> important than if you should even attempt it in the first place. >> On Dec 11, 2007, at 3:51 PM, Nishkar Grover wrote: >>> >>> I'm trying to replace a built-in exception type and here's a >>> simplified >>> example of what I was hoping to do... >>> >>> >>> >>> >>> import exceptions, __builtin__ >>> >>> >>> >>> zeroDivisionError = exceptions.ZeroDivisionError >>> >>> >>> >>> class Foo(zeroDivisionError): >>> ... bar = 'bar' >>> ... >>> >>> >>> >>> exceptions.ZeroDivisionError = Foo >>> >>> ZeroDivisionError = Foo >>> >>> __builtin__.ZeroDivisionError = Foo >>> >>> >>> >>> try: >>> ... raise ZeroDivisionError >>> ... except ZeroDivisionError, e: >>> ... print e.bar >>> ... >>> bar >>> >>> >>> >>> try: >>> ... 1/0 >>> ... except ZeroDivisionError, e: >>> ... print e.bar >>> ... >>> Traceback (most recent call last): >>> File "", line 2, in >>> ZeroDivisionError: integer division or modulo by zero >>> >>> >>> >>> Notice that I get my customized exception type when I explicitly >>> raise >>> ZeroDivisionError but not when that is implicitly raised by 1/0. It >>> seems like I have to replace that exception type at some lower >>> level, >>> but I'm not sure how/where. Does anyone know of a way to do this >>> >>> - Nishkar >>> >>> --http://mail.python.org/mailman/listinfo/python-list
VIEWS ON THIS POST

79

Posted on:

Wednesday 7th November 2012
View Replies!

abusing exceptions for continuations

i've had this strange idea of using the exception's traceback (which holds the stack frame) to enable functional continuations, meaning, raise some special exception which will be caught by a reactor/ scheduler/framework, which could later revive it by restoring the frame. i'm thinking of using the generator's implementation (some minimal support on the c-side) has this been tried before what were the results
VIEWS ON THIS POST

66

Posted on:

Wednesday 7th November 2012
View Replies!

Re: replacing built-in exception types

I'm trying to replace the built-in base exception class with a subclass of itself in python 2.5 because we can no longer add attributes to that... % python2.4 -c 'import exceptions; exceptions.Exception.bar = 1234' % python2.5 -c 'import exceptions; exceptions.Exception.bar = 1234' Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'exceptions.Exception' % python2.5 -c 'import exceptions; exceptions.BaseException.bar = 1234' Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'exceptions.BaseException' I already have a way to programatically construct the hierarchy of subclasses, so for example, my subclass of OSError is a subclass of the built-in OSError and a subclass of my subclass of EnvironmentError. The only thing left to do is find a way to replace the built-in exception types with my custom ones. - Nishkar Calvin Spealman wrote: > > Why would you do this How to do it, if its even possible, is far less > important than if you should even attempt it in the first place. > > > On Dec 11, 2007, at 3:51 PM, Nishkar Grover wrote: >> >> I'm trying to replace a built-in exception type and here's a simplified >> example of what I was hoping to do... >> >> >>> >> >>> import exceptions, __builtin__ >> >>> >> >>> zeroDivisionError = exceptions.ZeroDivisionError >> >>> >> >>> class Foo(zeroDivisionError): >> ... bar = 'bar' >> ... >> >>> >> >>> exceptions.ZeroDivisionError = Foo >> >>> ZeroDivisionError = Foo >> >>> __builtin__.ZeroDivisionError = Foo >> >>> >> >>> try: >> ... raise ZeroDivisionError >> ... except ZeroDivisionError, e: >> ... print e.bar >> ... >> bar >> >>> >> >>> try: >> ... 1/0 >> ... except ZeroDivisionError, e: >> ... print e.bar >> ... >> Traceback (most recent call last): >> File "", line 2, in >> ZeroDivisionError: integer division or modulo by zero >> >>> >> >> Notice that I get my customized exception type when I explicitly raise >> ZeroDivisionError but not when that is implicitly raised by 1/0. It >> seems like I have to replace that exception type at some lower level, >> but I'm not sure how/where. Does anyone know of a way to do this >> >> - Nishkar >> >> --http://mail.python.org/mailman/listinfo/python-list >
VIEWS ON THIS POST

79

Posted on:

Wednesday 7th November 2012
View Replies!

Pythonic way of reading a textfile line by line without throwing anexception

Hi , I'm a Python newbie but have experience programming PHP and C so i'm not really new to programming but new to Python. What's the "pythonic" way of reading a text file, line by line, without throwing an exception when there's nothing to be read I've been trying to map my while(!eof(fp)) mindset to the file object Python gives me when I call open() but have had no good results.
VIEWS ON THIS POST

146

Posted on:

Wednesday 7th November 2012
View Replies!

problem with change to exceptions

import exceptions class nothing (exceptions.Exception): def __init__ (self, args=None): self.args = args if __name__ == "__main__": raise nothing Traceback (most recent call last): File "", line 1, in File "/usr/tmp/python-3143hDH", line 5, in __init__ self.args = args TypeError: 'NoneType' object is not iterable I'll have to say, I don't understand this error.
VIEWS ON THIS POST

133

Posted on:

Wednesday 7th November 2012
View Replies!

Re-raising exceptions with modified message

What is the best way to re-raise any exception with a message supplemented with additional information (e.g. line number in a template) Let's say for simplicity I just want to add "sorry" to every exception message. My naive solution was this: try: ... except Exception, e: raise e.__class__, str(e) + ", sorry!" This works pretty well for most exceptions, e.g. >>> try: .... 1/0 .... except Exception, e: .... raise e.__class__, str(e) + ", sorry!" .... Traceback (most recent call last): File "", line 4, in ZeroDivisionError: integer division or modulo by zero, sorry! But it fails for some exceptions that cannot be instantiated with a single string argument, like UnicodeDecodeError which gets "converted" to a TypeError: >>> try: .... unicode('\xe4') .... except Exception, e: .... raise e.__class__, str(e) + ", sorry!" .... Traceback (most recent call last): File "", line 4, in TypeError: function takes exactly 5 arguments (1 given) Another approach is using a wrapper Extension class: class SorryEx(Exception): def __init__(self, e): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): return str(self._e) + ", sorry!" try: unicode('\xe4') except Exception, e: raise SorryEx(e) But then I get the name of the wrapper class in the message: __main__.SorryEx: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128), sorry! Yet another approach would be to replace the __str__ method of e, but this does not work for new style Exceptions (Python 2.5). Any suggestions -- Chris
VIEWS ON THIS POST

72

Posted on:

Saturday 10th November 2012
View Replies!

ironpython exception line number

, When an exeption occurs in a IronPython executet script, and I print the sys.exc , i get something ugly like the example below. How can I get the fileName and line number Thx in advance Troels 26-06-2007 13:19:04 : IronPython.Runtime.Exceptions.PythonIndentationError: unexpected token def ved IronPython.Compiler.SimpleParserSink.AddError(String path, String message, String lineText, CodeSpan span, Int32 errorCode, Severity severity) ved IronPython.Compiler.CompilerContext.AddError(String message, String lineText, Int32 startLine, Int32 startColumn, Int32 endLine, Int32 endColumn, Int32 errorCode, Severity severity) ved IronPython.Compiler.Parser.ReportSyntaxError(Location start, Location end, String message, Int32 errorCode) ved IronPython.Compiler.Parser.ReportSyntaxError(Token t, Int32 errorCode, Boolean allowIncomplete) ved IronPython.Compiler.Parser.ParseSuite() ved IronPython.Compiler.Parser.ParseFuncDef() ved IronPython.Compiler.Parser.ParseStmt() ved IronPython.Compiler.Parser.ParseSuite() ved IronPython.Compiler.Parser.ParseClassDef() ved IronPython.Compiler.Parser.ParseStmt() ved IronPython.Compiler.Parser.ParseFileInput() ved IronPython.Hosting.PythonEngine.Compile(Parser p, Boolean debuggingPossible) ved IronPython.Hosting.PythonEngine.CompileFile(String fileName) ved IronPython.Hosting.PythonEngine.ExecuteFile(String fileName)
VIEWS ON THIS POST

91

Posted on:

Saturday 10th November 2012
View Replies!

How can I obtain the exception object on a generlized except statement?

I am confused on one aspect of exception handling. If you specify the exception object type to match in an except statement it is possible to also obtain the exception object itself, but I can't figure out how to get ...
VIEWS ON THIS POST

104

Posted on:

Saturday 10th November 2012
View Replies!

handling unexpected exceptions in pdb

Hi all, I'm in an interactive session in pdb, debugging my code using pdb.runcall. Somewhere, an exception is raised and lands uncaught on stdout. Is there any way of picking up this exception and at least read the full message, ...
VIEWS ON THIS POST

92

Posted on:

Sunday 11th November 2012
View Replies!

User-defined exception: "global name 'TestRunError' is not defined"

I'm using some legacy code that has a user-defined exception in it. The top level program includes this line from TestRunError import * It also imports several other modules. These other modules do not explicitly import TestRunError. TestRunError is raised ...
VIEWS ON THIS POST

53

Posted on:

Sunday 11th November 2012
View Replies!

handlers.SocketHandler and exceptions

Hi all, On our Linux systems at work I've written a Twisted logging server that receives log messages from multiple servers/processes to post them to a log file, essentially serializing all the process log messages. This works well, that is ...
VIEWS ON THIS POST

42

Posted on:

Sunday 11th November 2012
View Replies!

exception message output problem

I am baffled about why my exception messages are not displaying properly. I have a class that represents physical scalars with units. If I type >>> 3 * s + 4 * m I should get something like this: scalar.InconsistentUnits: ...
VIEWS ON THIS POST

98

Posted on:

Monday 12th November 2012
View Replies!

Can I hide internal method calls from an exception stack trace?

Is there any way to hide portions of an exception stack trace When users get exceptions when using pyparsing, there are usually many layers of pyparsing-internal stack messages that are not at all helpful in diagnosing the problem - the ...
VIEWS ON THIS POST

48

Posted on:

Saturday 24th November 2012
View Replies!

RE: exception handling in complex Python programs

Lie wrote: > Ah... now I understand what the Zen is talking about when it said: > "Now is better then never, although never is often better than *right* > now." If you don't have all the necessary resources to ...
VIEWS ON THIS POST

62

Posted on:

Sunday 25th November 2012
View Replies!

How do i : Python Threads + KeyboardInterrupt exception

Hi all, I have a small python project i am working on. Basically i always have two threads. A "Read" thread that sits in a loop reading a line at a time from some input (Usually stdin) and then generating ...
VIEWS ON THIS POST

70

Posted on:

Sunday 25th November 2012
View Replies!