views:

88

answers:

3

I have a class whose methods require that a certain class field exists correctly. That class field is set in the constructor and it's read from a config file, and it may or may not get the correct data from that config file. If the data is incorrect, it will have the wrong data in the class field and the class method will throw an exception.

If that happens, what I want to do is run the method again but with a different call to the class constructor. Is this something that is reasonably handled in a try:catch? Because the method MAY throw the same exception even with the correct class field. So what I want is to have the first time the method is called, the exception is caught and then the method run again. But on the 2nd run if the exception is thrown I want it to propagate. So:


try:
    MyClass().method()
except MyException:
    MyClass(True).method()

Is there an obvious flaw to this? Or a better way to do this without using counters, or flags, or other ugly helper objects?

+1  A: 

What you're doing is fine; if the method throws the same exception from within the exception handler, it will be propagated and not caught by the same handler.

Tamás
+2  A: 

I'm a bit surprised that you don't want the MyClass instance to stick around for later use, but, given that this is your intention, your code is correct and concise -- it does what you state you want without any "obvious flaw". I'm not sure which objects you think ugly and which ones you think pretty, but without introducing some "helper objects" I can't even think of another way to achieve your stated requirements!-)

Alex Martelli
This is just part of a much larger program that would be much too long to post. And there's a lot of non __python__ things that would probably be nice to change if it were to be written again, but let's just say there's lots of classes that consist of only static methods
Falmarri
@Falmarri, if a method is static you don't need to instantiate the class in order to call it -- that's the whole point of having the method be _static_ after all (in any of Python, C++, Java, ...).
Alex Martelli
Yeah, that was just an example of the non pythonic stuff we have -P
Falmarri
A: 

Sounds like you're talking about sort of Factory method. I would create a separate Creator class to handle such situation.

dmitko