Python way to avoid usage of raise

classic Classic list List threaded Threaded
22 messages Options
12
Reply | Threaded
Open this post in threaded view
|

Python way to avoid usage of raise

Nick S Kanakakorn
Hi,

My work place has imposed a rules for no use of exception (catching is allowed).  If I have code like this

def f1()
  if bad_thing_happen():
     raise Exception('bad stuff')
  ...
  return something

I could change it to

def f1()
  if bad_thing_happen():
    return [-1, None]
  ...
  return [0, something]

f1 caller would be like this

def f1_caller():
  code, result = f1(param1)
  if code < 0:
    return code
  actual_work1()
  # call f1 again
  code, result = f1(param2)
  if code < 0:
    return code
  actual_work2()
  ...

Are there more elegant ways than this in Python ?

Thanks,
Nick K


_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Glen Jarvis

> My work place has imposed a rules for no use of exception (catching is allowed).

What?!?

Forgive my reaction, I'm just very surprised. Why has your workplace implemented this policy? Has anyone else on BayPIGgies seen a  policy like this? What's the rationale?  Am I a Luddite for not hearing on this?

I'm sorry. I know you asked a genuine question and I haven't answered it. I just found this very odd and am first getting my head around the question.

Cheers,


Glen

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Daniel González Gasull-2
I agree.  That's an anti-pattern:

http://today.java.net/article/2006/04/04/exception-handling-antipatterns

The article is about Java, but it applies anyway.  See where it says
"Log and Return Null".


On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:

>
>> My work place has imposed a rules for no use of exception (catching is allowed).
>
> What?!?
>
> Forgive my reaction, I'm just very surprised. Why has your workplace implemented this policy? Has anyone else on BayPIGgies seen a  policy like this? What's the rationale?  Am I a Luddite for not hearing on this?
>
> I'm sorry. I know you asked a genuine question and I haven't answered it. I just found this very odd and am first getting my head around the question.
>
> Cheers,
>
>
> Glen
>
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>



--
http://DjanSoft.com :: Agile Application Development with Python
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Zachary Collins
I know.  You should devise a way for your f1_caller to be able to
determine if there's an issue inside of f1, and have it just
automatically back out of f1_caller itself, and then inform the caller
of f1_caller.  Something that you could just add inside of f1 in one
place, that informed as far back in the stack as is responsible for
the data issue in f1.  Something that maybe allowed you to make caller
functions aware of an error, elegantly... hmmmmmmmm

2010/10/5 Daniel González Gasull <[hidden email]>:

> I agree.  That's an anti-pattern:
>
> http://today.java.net/article/2006/04/04/exception-handling-antipatterns
>
> The article is about Java, but it applies anyway.  See where it says
> "Log and Return Null".
>
>
> On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:
>>
>>> My work place has imposed a rules for no use of exception (catching is allowed).
>>
>> What?!?
>>
>> Forgive my reaction, I'm just very surprised. Why has your workplace implemented this policy? Has anyone else on BayPIGgies seen a  policy like this? What's the rationale?  Am I a Luddite for not hearing on this?
>>
>> I'm sorry. I know you asked a genuine question and I haven't answered it. I just found this very odd and am first getting my head around the question.
>>
>> Cheers,
>>
>>
>> Glen
>>
>> _______________________________________________
>> Baypiggies mailing list
>> [hidden email]
>> To change your subscription options or unsubscribe:
>> http://mail.python.org/mailman/listinfo/baypiggies
>>
>
>
>
> --
> http://DjanSoft.com :: Agile Application Development with Python
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Nick S Kanakakorn
In reply to this post by Glen Jarvis
Let's skip the rationale discussion although I feel better for your sympathy.  One non python solution I can think of is Macro (C/C++) or add a new command  which could work in any stack frame (TCL).
However, I'm quite new to python so I'm not so sure if there are some ways around this.

Can we have something similar to macro in python ?

On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:

> My work place has imposed a rules for no use of exception (catching is allowed).

What?!?

Forgive my reaction, I'm just very surprised. Why has your workplace implemented this policy? Has anyone else on BayPIGgies seen a  policy like this? What's the rationale?  Am I a Luddite for not hearing on this?

I'm sorry. I know you asked a genuine question and I haven't answered it. I just found this very odd and am first getting my head around the question.

Cheers,


Glen




--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Jamie Tatum
In reply to this post by Nick S Kanakakorn
On Tue, Oct 5, 2010 at 7:15 PM, Nick S Kanakakorn <[hidden email]> wrote:
> Hi,
> My work place has imposed a rules for no use of exception (catching is
> allowed).  If I have code like this

I've seen this anti-pattern up close. There is no Pythonic answer -
exceptions are the answer. I've adapted this recipe[0] to get all
kinds of information from the call stack when something fails,
although it depends on the failing function to call it... Definitely a
pain. I feel for you. Hopefully the code is solid enough not to need
too much debugging.

For the curious, the rationale I heard is that failure isn't important
enough to stop the execution or the minor variant, failures are
irrelevant to the execution.

[0] http://code.activestate.com/recipes/52215/
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Tung Wai Yip
In reply to this post by Nick S Kanakakorn
Why do you want to do this? Is this just an internal coding guideline? Or  
is it done for interfacing to another language or running on non-standard  
VM? Is this apply to new code only or do you want to update existing code  
as well?

There is no equivalent of C macro in Python. Just apply every code change  
as you describe it. Build a tuple every time you return something. Change  
raise into returning tuple. And change ever function call to expecting a  
tuple return value. I can't think of anything smarter. it looks like a  
complete disaster anyway.

Wai yip



> Let's skip the rationale discussion although I feel better for your
> sympathy.  One non python solution I can think of is Macro (C/C++) or  
> add a
> new command  which could work in any stack frame (TCL).
> However, I'm quite new to python so I'm not so sure if there are some  
> ways
> around this.
>
> Can we have something similar to macro in python ?
>
> On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:
>
>>
>> > My work place has imposed a rules for no use of exception (catching is
>> allowed).
>>
>> What?!?
>>
>> Forgive my reaction, I'm just very surprised. Why has your workplace
>> implemented this policy? Has anyone else on BayPIGgies seen a  policy  
>> like
>> this? What's the rationale?  Am I a Luddite for not hearing on this?
>>
>> I'm sorry. I know you asked a genuine question and I haven't answered  
>> it. I
>> just found this very odd and am first getting my head around the  
>> question.
>>
>> Cheers,
>>
>>
>> Glen
>>
>>
>
>


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Nick S Kanakakorn
I don't want to do this.  There is someone that against throwing exception and that person has more seniority than me. He put in a guideline.  I lost in the debate.  There is no proper research done and all the decisions were made in less than 1 day. 

On Tue, Oct 5, 2010 at 9:03 PM, Tung Wai Yip <[hidden email]> wrote:
Why do you want to do this? Is this just an internal coding guideline? Or is it done for interfacing to another language or running on non-standard VM? Is this apply to new code only or do you want to update existing code as well?

There is no equivalent of C macro in Python. Just apply every code change as you describe it. Build a tuple every time you return something. Change raise into returning tuple. And change ever function call to expecting a tuple return value. I can't think of anything smarter. it looks like a complete disaster anyway.

Wai yip




Let's skip the rationale discussion although I feel better for your
sympathy.  One non python solution I can think of is Macro (C/C++) or add a
new command  which could work in any stack frame (TCL).
However, I'm quite new to python so I'm not so sure if there are some ways
around this.

Can we have something similar to macro in python ?

On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:


> My work place has imposed a rules for no use of exception (catching is
allowed).

What?!?

Forgive my reaction, I'm just very surprised. Why has your workplace
implemented this policy? Has anyone else on BayPIGgies seen a  policy like
this? What's the rationale?  Am I a Luddite for not hearing on this?

I'm sorry. I know you asked a genuine question and I haven't answered it. I
just found this very odd and am first getting my head around the question.

Cheers,


Glen






--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies



--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Tung Wai Yip
In reply to this post by Jamie Tatum
The recipe only collect information from the stack. It won't resume  
execution after an exception is throw.

It maybe easier to use a wrapper for all function call.


>>> def call(func, *args, **kwargs):
...   try:
...     return func(*args,**kwargs)
...   except:
...     # auto ignore exception!
...     return
...
>>> res = call(open,'dummy file','rb')
>>> # look mom, no exception!

Wai Yip



> On Tue, Oct 5, 2010 at 7:15 PM, Nick S Kanakakorn <[hidden email]>  
> wrote:
>> Hi,
>> My work place has imposed a rules for no use of exception (catching is
>> allowed).  If I have code like this
>
> I've seen this anti-pattern up close. There is no Pythonic answer -
> exceptions are the answer. I've adapted this recipe[0] to get all
> kinds of information from the call stack when something fails,
> although it depends on the failing function to call it... Definitely a
> pain. I feel for you. Hopefully the code is solid enough not to need
> too much debugging.
>
> For the curious, the rationale I heard is that failure isn't important
> enough to stop the execution or the minor variant, failures are
> irrelevant to the execution.
>
> [0] http://code.activestate.com/recipes/52215/
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Steve Lacy
If you're not allowed to raise the exception, why not just return it?

I can imagine a pattern where every function was a tuple return value (as stated previously) where the first item is the real return value, and the 2nd item is either None or an instance of an Exception. 

Then, you could wrap every function in your entire system with a decorator that looked at these return values, and if the Exception part was non-None, then it would return back out to the caller, possibly calling some cleanup function that would be specified as an argument to the decorator.  I can code up some kind of rudimentary example if you'd like. 

Of course, this path gets dangerously close to "let's do exactly the same thing as exceptions but not use the built in language features ourselves and rewrite the whole thing from scratch so we have a maintenance nightmare".  

Is it too late to quit and go work somewhere else?

Steve

On Tue, Oct 5, 2010 at 9:20 PM, Tung Wai Yip <[hidden email]> wrote:
The recipe only collect information from the stack. It won't resume execution after an exception is throw.

It maybe easier to use a wrapper for all function call.


def call(func, *args, **kwargs):
...   try:
...     return func(*args,**kwargs)
...   except:
...     # auto ignore exception!
...     return
...
res = call(open,'dummy file','rb')
# look mom, no exception!

Wai Yip




On Tue, Oct 5, 2010 at 7:15 PM, Nick S Kanakakorn <[hidden email]> wrote:
Hi,
My work place has imposed a rules for no use of exception (catching is
allowed).  If I have code like this

I've seen this anti-pattern up close. There is no Pythonic answer -
exceptions are the answer. I've adapted this recipe[0] to get all
kinds of information from the call stack when something fails,
although it depends on the failing function to call it... Definitely a
pain. I feel for you. Hopefully the code is solid enough not to need
too much debugging.

For the curious, the rationale I heard is that failure isn't important
enough to stop the execution or the minor variant, failures are
irrelevant to the execution.

[0] http://code.activestate.com/recipes/52215/
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies


_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Andy Wiggin
In reply to this post by Nick S Kanakakorn
I must agree with the "it's an unmitigated disaster" comments already
posted. But it does remind me of a C coding convention that was the
standard at a company worked at a long time ago. Here, the return
value from a function was always a coded int value where part of the
int told you the boolean pass/fail info, part encoded the severity,
part the product id, and part the specific message that could be
looked up to print. All packed into 32 bits. The analogy I can think
of is that you might want to return an instance of a standard class
instead of a raw tuple. It could have pass/fail info, perhaps more
extended info, plus a generic "payload" that would carry whatever the
function was really trying to return. This would at least save you
from interpreting ad hoc tuples everywhere, and might be a basis for
building something a bit more elegant.

-Andy

On Tue, Oct 5, 2010 at 9:16 PM, Nick S Kanakakorn <[hidden email]> wrote:

> I don't want to do this.  There is someone that against throwing exception
> and that person has more seniority than me. He put in a guideline.  I lost
> in the debate.  There is no proper research done and all the decisions were
> made in less than 1 day.
>
> On Tue, Oct 5, 2010 at 9:03 PM, Tung Wai Yip <[hidden email]> wrote:
>>
>> Why do you want to do this? Is this just an internal coding guideline? Or
>> is it done for interfacing to another language or running on non-standard
>> VM? Is this apply to new code only or do you want to update existing code as
>> well?
>>
>> There is no equivalent of C macro in Python. Just apply every code change
>> as you describe it. Build a tuple every time you return something. Change
>> raise into returning tuple. And change ever function call to expecting a
>> tuple return value. I can't think of anything smarter. it looks like a
>> complete disaster anyway.
>>
>> Wai yip
>>
>>
>>
>>> Let's skip the rationale discussion although I feel better for your
>>> sympathy.  One non python solution I can think of is Macro (C/C++) or add
>>> a
>>> new command  which could work in any stack frame (TCL).
>>> However, I'm quite new to python so I'm not so sure if there are some
>>> ways
>>> around this.
>>>
>>> Can we have something similar to macro in python ?
>>>
>>> On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:
>>>
>>>>
>>>> > My work place has imposed a rules for no use of exception (catching is
>>>> allowed).
>>>>
>>>> What?!?
>>>>
>>>> Forgive my reaction, I'm just very surprised. Why has your workplace
>>>> implemented this policy? Has anyone else on BayPIGgies seen a  policy
>>>> like
>>>> this? What's the rationale?  Am I a Luddite for not hearing on this?
>>>>
>>>> I'm sorry. I know you asked a genuine question and I haven't answered
>>>> it. I
>>>> just found this very odd and am first getting my head around the
>>>> question.
>>>>
>>>> Cheers,
>>>>
>>>>
>>>> Glen
>>>>
>>>>
>>>
>>>
>>
>>
>> --
>> Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
>> _______________________________________________
>> Baypiggies mailing list
>> [hidden email]
>> To change your subscription options or unsubscribe:
>> http://mail.python.org/mailman/listinfo/baypiggies
>
>
>
> --
> -Nick Kanakakorn
>
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Nick S Kanakakorn
Hi Andy,

Thanks for your comment.  I could wrap this in a class but I'm not so sure how it would save me to have to do something like this.

class ReturnWrapper(object):
     def __init__(error_code, error_message, real_return_result)
           ....

def f1(arg):
    try
        x = some_function()
    except IndexError, e
        return ReturnWrapper(-1,'some error message' , None)
    # all good here
    return ReturnWrapper(0, None, 'some good value')

def f1caller()
    obj = f1(param1)
    if (obj.error_code < 0):
       # handle some error or just return obj
       return obj
    foo....
    obj = f1(param2)
    if (obj.error_code < 0):
       # handle some error or just return obj
       return obj
    bar....


I still have to use this pattern     if (obj.error_code < 0):  .... 
It does not really make my code smaller than using tuple.
I used to code C similar to what you said I did not expect to have to do the 
same thing in python

Thanks,

On Tue, Oct 5, 2010 at 9:42 PM, Andy Wiggin <[hidden email]> wrote:
I must agree with the "it's an unmitigated disaster" comments already
posted. But it does remind me of a C coding convention that was the
standard at a company worked at a long time ago. Here, the return
value from a function was always a coded int value where part of the
int told you the boolean pass/fail info, part encoded the severity,
part the product id, and part the specific message that could be
looked up to print. All packed into 32 bits. The analogy I can think
of is that you might want to return an instance of a standard class
instead of a raw tuple. It could have pass/fail info, perhaps more
extended info, plus a generic "payload" that would carry whatever the
function was really trying to return. This would at least save you
from interpreting ad hoc tuples everywhere, and might be a basis for
building something a bit more elegant.

-Andy

On Tue, Oct 5, 2010 at 9:16 PM, Nick S Kanakakorn <[hidden email]> wrote:
> I don't want to do this.  There is someone that against throwing exception
> and that person has more seniority than me. He put in a guideline.  I lost
> in the debate.  There is no proper research done and all the decisions were
> made in less than 1 day.
>
> On Tue, Oct 5, 2010 at 9:03 PM, Tung Wai Yip <[hidden email]> wrote:
>>
>> Why do you want to do this? Is this just an internal coding guideline? Or
>> is it done for interfacing to another language or running on non-standard
>> VM? Is this apply to new code only or do you want to update existing code as
>> well?
>>
>> There is no equivalent of C macro in Python. Just apply every code change
>> as you describe it. Build a tuple every time you return something. Change
>> raise into returning tuple. And change ever function call to expecting a
>> tuple return value. I can't think of anything smarter. it looks like a
>> complete disaster anyway.
>>
>> Wai yip
>>
>>
>>
>>> Let's skip the rationale discussion although I feel better for your
>>> sympathy.  One non python solution I can think of is Macro (C/C++) or add
>>> a
>>> new command  which could work in any stack frame (TCL).
>>> However, I'm quite new to python so I'm not so sure if there are some
>>> ways
>>> around this.
>>>
>>> Can we have something similar to macro in python ?
>>>
>>> On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]> wrote:
>>>
>>>>
>>>> > My work place has imposed a rules for no use of exception (catching is
>>>> allowed).
>>>>
>>>> What?!?
>>>>
>>>> Forgive my reaction, I'm just very surprised. Why has your workplace
>>>> implemented this policy? Has anyone else on BayPIGgies seen a  policy
>>>> like
>>>> this? What's the rationale?  Am I a Luddite for not hearing on this?
>>>>
>>>> I'm sorry. I know you asked a genuine question and I haven't answered
>>>> it. I
>>>> just found this very odd and am first getting my head around the
>>>> question.
>>>>
>>>> Cheers,
>>>>
>>>>
>>>> Glen
>>>>
>>>>
>>>
>>>
>>
>>
>> --
>> Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
>> _______________________________________________
>> Baypiggies mailing list
>> [hidden email]
>> To change your subscription options or unsubscribe:
>> http://mail.python.org/mailman/listinfo/baypiggies
>
>
>
> --
> -Nick Kanakakorn
>
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>



--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Andy Wiggin
Right. I couldn't get past that part either, at least based on what I
know about coding in pure python. When we did this in C of course we
used macros to wrap the standard return-on-error-of-child behavior and
every now and then wrote something more sophisticated (oh! Just like
an exception, except with extra text obscuring the code). So short of
using a macro-preprocessor to generate your python files, you can at
least standardize and condense the one-liner after each function call.
Here's what I came up with:


class FuncStatus:
    def __init__(self, success, payload):
        self.success = success
        self.payload = payload
    def err(self):
        return not self.success

def sub_test(v):
    if v > 0:
        return FuncStatus(True, "a b c")
    else:
        return FuncStatus(False, ["d", "e", "f"])

def main():
    #if (s = sub_test(-2)).err() return s
    s = sub_test(2)
    if s.err(): return s
    print "Hey 1", s.payload

    s = sub_test(-2)
    if s.err(): return s
    print "Hey 2", s.payload

main()

-Andy

On Tue, Oct 5, 2010 at 10:32 PM, Nick S Kanakakorn <[hidden email]> wrote:

> Hi Andy,
> Thanks for your comment.  I could wrap this in a class but I'm not so sure
> how it would save me to have to do something like this.
> class ReturnWrapper(object):
>      def __init__(error_code, error_message, real_return_result)
>            ....
> def f1(arg):
>     try
>         x = some_function()
>     except IndexError, e
>         return ReturnWrapper(-1,'some error message' , None)
>     # all good here
>     return ReturnWrapper(0, None, 'some good value')
> def f1caller()
>     obj = f1(param1)
>     if (obj.error_code < 0):
>        # handle some error or just return obj
>        return obj
>     foo....
>     obj = f1(param2)
>     if (obj.error_code < 0):
>        # handle some error or just return obj
>        return obj
>     bar....
>
> I still have to use this pattern     if (obj.error_code < 0):  ....
> It does not really make my code smaller than using tuple.
> I used to code C similar to what you said I did not expect to have to do
> the
> same thing in python
> Thanks,
> On Tue, Oct 5, 2010 at 9:42 PM, Andy Wiggin <[hidden email]> wrote:
>>
>> I must agree with the "it's an unmitigated disaster" comments already
>> posted. But it does remind me of a C coding convention that was the
>> standard at a company worked at a long time ago. Here, the return
>> value from a function was always a coded int value where part of the
>> int told you the boolean pass/fail info, part encoded the severity,
>> part the product id, and part the specific message that could be
>> looked up to print. All packed into 32 bits. The analogy I can think
>> of is that you might want to return an instance of a standard class
>> instead of a raw tuple. It could have pass/fail info, perhaps more
>> extended info, plus a generic "payload" that would carry whatever the
>> function was really trying to return. This would at least save you
>> from interpreting ad hoc tuples everywhere, and might be a basis for
>> building something a bit more elegant.
>>
>> -Andy
>>
>> On Tue, Oct 5, 2010 at 9:16 PM, Nick S Kanakakorn <[hidden email]>
>> wrote:
>> > I don't want to do this.  There is someone that against throwing
>> > exception
>> > and that person has more seniority than me. He put in a guideline.  I
>> > lost
>> > in the debate.  There is no proper research done and all the decisions
>> > were
>> > made in less than 1 day.
>> >
>> > On Tue, Oct 5, 2010 at 9:03 PM, Tung Wai Yip <[hidden email]>
>> > wrote:
>> >>
>> >> Why do you want to do this? Is this just an internal coding guideline?
>> >> Or
>> >> is it done for interfacing to another language or running on
>> >> non-standard
>> >> VM? Is this apply to new code only or do you want to update existing
>> >> code as
>> >> well?
>> >>
>> >> There is no equivalent of C macro in Python. Just apply every code
>> >> change
>> >> as you describe it. Build a tuple every time you return something.
>> >> Change
>> >> raise into returning tuple. And change ever function call to expecting
>> >> a
>> >> tuple return value. I can't think of anything smarter. it looks like a
>> >> complete disaster anyway.
>> >>
>> >> Wai yip
>> >>
>> >>
>> >>
>> >>> Let's skip the rationale discussion although I feel better for your
>> >>> sympathy.  One non python solution I can think of is Macro (C/C++) or
>> >>> add
>> >>> a
>> >>> new command  which could work in any stack frame (TCL).
>> >>> However, I'm quite new to python so I'm not so sure if there are some
>> >>> ways
>> >>> around this.
>> >>>
>> >>> Can we have something similar to macro in python ?
>> >>>
>> >>> On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]>
>> >>> wrote:
>> >>>
>> >>>>
>> >>>> > My work place has imposed a rules for no use of exception (catching
>> >>>> > is
>> >>>> allowed).
>> >>>>
>> >>>> What?!?
>> >>>>
>> >>>> Forgive my reaction, I'm just very surprised. Why has your workplace
>> >>>> implemented this policy? Has anyone else on BayPIGgies seen a  policy
>> >>>> like
>> >>>> this? What's the rationale?  Am I a Luddite for not hearing on this?
>> >>>>
>> >>>> I'm sorry. I know you asked a genuine question and I haven't answered
>> >>>> it. I
>> >>>> just found this very odd and am first getting my head around the
>> >>>> question.
>> >>>>
>> >>>> Cheers,
>> >>>>
>> >>>>
>> >>>> Glen
>> >>>>
>> >>>>
>> >>>
>> >>>
>> >>
>> >>
>> >> --
>> >> Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
>> >> _______________________________________________
>> >> Baypiggies mailing list
>> >> [hidden email]
>> >> To change your subscription options or unsubscribe:
>> >> http://mail.python.org/mailman/listinfo/baypiggies
>> >
>> >
>> >
>> > --
>> > -Nick Kanakakorn
>> >
>> > _______________________________________________
>> > Baypiggies mailing list
>> > [hidden email]
>> > To change your subscription options or unsubscribe:
>> > http://mail.python.org/mailman/listinfo/baypiggies
>> >
>
>
>
> --
> -Nick Kanakakorn
>
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Nick S Kanakakorn
Andy,

Thanks so much.

-Nick

On Tue, Oct 5, 2010 at 11:33 PM, Andy Wiggin <[hidden email]> wrote:
Right. I couldn't get past that part either, at least based on what I
know about coding in pure python. When we did this in C of course we
used macros to wrap the standard return-on-error-of-child behavior and
every now and then wrote something more sophisticated (oh! Just like
an exception, except with extra text obscuring the code). So short of
using a macro-preprocessor to generate your python files, you can at
least standardize and condense the one-liner after each function call.
Here's what I came up with:


class FuncStatus:
   def __init__(self, success, payload):
       self.success = success
       self.payload = payload
   def err(self):
       return not self.success

def sub_test(v):
   if v > 0:
       return FuncStatus(True, "a b c")
   else:
       return FuncStatus(False, ["d", "e", "f"])

def main():
   #if (s = sub_test(-2)).err() return s
   s = sub_test(2)
   if s.err(): return s
   print "Hey 1", s.payload

   s = sub_test(-2)
   if s.err(): return s
   print "Hey 2", s.payload

main()

-Andy

On Tue, Oct 5, 2010 at 10:32 PM, Nick S Kanakakorn <[hidden email]> wrote:
> Hi Andy,
> Thanks for your comment.  I could wrap this in a class but I'm not so sure
> how it would save me to have to do something like this.
> class ReturnWrapper(object):
>      def __init__(error_code, error_message, real_return_result)
>            ....
> def f1(arg):
>     try
>         x = some_function()
>     except IndexError, e
>         return ReturnWrapper(-1,'some error message' , None)
>     # all good here
>     return ReturnWrapper(0, None, 'some good value')
> def f1caller()
>     obj = f1(param1)
>     if (obj.error_code < 0):
>        # handle some error or just return obj
>        return obj
>     foo....
>     obj = f1(param2)
>     if (obj.error_code < 0):
>        # handle some error or just return obj
>        return obj
>     bar....
>
> I still have to use this pattern     if (obj.error_code < 0):  ....
> It does not really make my code smaller than using tuple.
> I used to code C similar to what you said I did not expect to have to do
> the
> same thing in python
> Thanks,
> On Tue, Oct 5, 2010 at 9:42 PM, Andy Wiggin <[hidden email]> wrote:
>>
>> I must agree with the "it's an unmitigated disaster" comments already
>> posted. But it does remind me of a C coding convention that was the
>> standard at a company worked at a long time ago. Here, the return
>> value from a function was always a coded int value where part of the
>> int told you the boolean pass/fail info, part encoded the severity,
>> part the product id, and part the specific message that could be
>> looked up to print. All packed into 32 bits. The analogy I can think
>> of is that you might want to return an instance of a standard class
>> instead of a raw tuple. It could have pass/fail info, perhaps more
>> extended info, plus a generic "payload" that would carry whatever the
>> function was really trying to return. This would at least save you
>> from interpreting ad hoc tuples everywhere, and might be a basis for
>> building something a bit more elegant.
>>
>> -Andy
>>
>> On Tue, Oct 5, 2010 at 9:16 PM, Nick S Kanakakorn <[hidden email]>
>> wrote:
>> > I don't want to do this.  There is someone that against throwing
>> > exception
>> > and that person has more seniority than me. He put in a guideline.  I
>> > lost
>> > in the debate.  There is no proper research done and all the decisions
>> > were
>> > made in less than 1 day.
>> >
>> > On Tue, Oct 5, 2010 at 9:03 PM, Tung Wai Yip <[hidden email]>
>> > wrote:
>> >>
>> >> Why do you want to do this? Is this just an internal coding guideline?
>> >> Or
>> >> is it done for interfacing to another language or running on
>> >> non-standard
>> >> VM? Is this apply to new code only or do you want to update existing
>> >> code as
>> >> well?
>> >>
>> >> There is no equivalent of C macro in Python. Just apply every code
>> >> change
>> >> as you describe it. Build a tuple every time you return something.
>> >> Change
>> >> raise into returning tuple. And change ever function call to expecting
>> >> a
>> >> tuple return value. I can't think of anything smarter. it looks like a
>> >> complete disaster anyway.
>> >>
>> >> Wai yip
>> >>
>> >>
>> >>
>> >>> Let's skip the rationale discussion although I feel better for your
>> >>> sympathy.  One non python solution I can think of is Macro (C/C++) or
>> >>> add
>> >>> a
>> >>> new command  which could work in any stack frame (TCL).
>> >>> However, I'm quite new to python so I'm not so sure if there are some
>> >>> ways
>> >>> around this.
>> >>>
>> >>> Can we have something similar to macro in python ?
>> >>>
>> >>> On Tue, Oct 5, 2010 at 7:27 PM, Glen Jarvis <[hidden email]>
>> >>> wrote:
>> >>>
>> >>>>
>> >>>> > My work place has imposed a rules for no use of exception (catching
>> >>>> > is
>> >>>> allowed).
>> >>>>
>> >>>> What?!?
>> >>>>
>> >>>> Forgive my reaction, I'm just very surprised. Why has your workplace
>> >>>> implemented this policy? Has anyone else on BayPIGgies seen a  policy
>> >>>> like
>> >>>> this? What's the rationale?  Am I a Luddite for not hearing on this?
>> >>>>
>> >>>> I'm sorry. I know you asked a genuine question and I haven't answered
>> >>>> it. I
>> >>>> just found this very odd and am first getting my head around the
>> >>>> question.
>> >>>>
>> >>>> Cheers,
>> >>>>
>> >>>>
>> >>>> Glen
>> >>>>
>> >>>>
>> >>>
>> >>>
>> >>
>> >>
>> >> --
>> >> Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
>> >> _______________________________________________
>> >> Baypiggies mailing list
>> >> [hidden email]
>> >> To change your subscription options or unsubscribe:
>> >> http://mail.python.org/mailman/listinfo/baypiggies
>> >
>> >
>> >
>> > --
>> > -Nick Kanakakorn
>> >
>> > _______________________________________________
>> > Baypiggies mailing list
>> > [hidden email]
>> > To change your subscription options or unsubscribe:
>> > http://mail.python.org/mailman/listinfo/baypiggies
>> >
>
>
>
> --
> -Nick Kanakakorn
>



--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Andrew Dalke
In reply to this post by Jamie Tatum
On Oct 5, 2010, at 9:57 PM, James Tatum wrote:
> I've seen this anti-pattern up close. There is no Pythonic answer -
> exceptions are the answer.

There is a Pythonic answer - you can go the Twisted route.
(Excepting those who think Twisted isn't Pythonic. ;)

Twisted's Deferreds can't use the stack because they
implement continuations through callback methods. You
"addCallback" for the normal case and "addErrback" for the
exceptions.

It's possible to develop your entire code base this way.

It's going to be structured entirely different than what
the OP's more senior rule mandator expects, but that might
be a good thing here.


                                Andrew
                                [hidden email]


_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Brent Tubbs
Nick: Is your boss likely to notice something like this?

(except.py)
class TotallyNotAnExceptionNothingToSeeHere(Exception):
    pass

raise TotallyNotAnExceptionNothingToSeeHere("Really, pay me no attention")

brent@greta:~/tmp$ python except.py
Traceback (most recent call last):
  File "except.py", line 4, in <module>
    raise TotallyNotAnExceptionNothingToSeeHere("Really, pay me no attention")
__main__.TotallyNotAnExceptionNothingToSeeHere: Really, pay me no attention

Kidding.... mostly.  The "no exceptions" rule just seems really arbitrary.

Brent

On Wed, Oct 6, 2010 at 8:01 AM, Andrew Dalke <[hidden email]> wrote:

> On Oct 5, 2010, at 9:57 PM, James Tatum wrote:
>> I've seen this anti-pattern up close. There is no Pythonic answer -
>> exceptions are the answer.
>
> There is a Pythonic answer - you can go the Twisted route.
> (Excepting those who think Twisted isn't Pythonic. ;)
>
> Twisted's Deferreds can't use the stack because they
> implement continuations through callback methods. You
> "addCallback" for the normal case and "addErrback" for the
> exceptions.
>
> It's possible to develop your entire code base this way.
>
> It's going to be structured entirely different than what
> the OP's more senior rule mandator expects, but that might
> be a good thing here.
>
>
>                                Andrew
>                                [hidden email]
>
>
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Nick S Kanakakorn
In reply to this post by Nick S Kanakakorn
There is a happy news here today.  The use of raise exception is allowed again after I put some coding in using this convention:

exitcode, actual_result = f1()
if exitcode < 0: return exitcode
.... continue something useful with actual_result
exitcode, actual_result = f1()



On Tue, Oct 5, 2010 at 7:15 PM, Nick S Kanakakorn <[hidden email]> wrote:
Hi,

My work place has imposed a rules for no use of exception (catching is allowed).  If I have code like this

def f1()
  if bad_thing_happen():
     raise Exception('bad stuff')
  ...
  return something

I could change it to

def f1()
  if bad_thing_happen():
    return [-1, None]
  ...
  return [0, something]

f1 caller would be like this

def f1_caller():
  code, result = f1(param1)
  if code < 0:
    return code
  actual_work1()
  # call f1 again
  code, result = f1(param2)
  if code < 0:
    return code
  actual_work2()
  ...

Are there more elegant ways than this in Python ?

Thanks,
Nick K




--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

DeLuca, Todd
In reply to this post by Nick S Kanakakorn
You could raise some exceptions without the word 'raise'.

>>> 'a' + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects


Todd DeLuca
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Nick S Kanakakorn
In reply to this post by Brent Tubbs
Brent,

The rules changed after one day.  Now, I can use exception again.  
Off topics: if python have command alias, I can say 'alias error raise'

-Nick

On Wed, Oct 6, 2010 at 2:28 PM, Brent Tubbs <[hidden email]> wrote:
Nick: Is your boss likely to notice something like this?

(except.py)
class TotallyNotAnExceptionNothingToSeeHere(Exception):
   pass

raise TotallyNotAnExceptionNothingToSeeHere("Really, pay me no attention")

brent@greta:~/tmp$ python except.py
Traceback (most recent call last):
 File "except.py", line 4, in <module>
   raise TotallyNotAnExceptionNothingToSeeHere("Really, pay me no attention")
__main__.TotallyNotAnExceptionNothingToSeeHere: Really, pay me no attention

Kidding.... mostly.  The "no exceptions" rule just seems really arbitrary.

Brent

On Wed, Oct 6, 2010 at 8:01 AM, Andrew Dalke <[hidden email]> wrote:
> On Oct 5, 2010, at 9:57 PM, James Tatum wrote:
>> I've seen this anti-pattern up close. There is no Pythonic answer -
>> exceptions are the answer.
>
> There is a Pythonic answer - you can go the Twisted route.
> (Excepting those who think Twisted isn't Pythonic. ;)
>
> Twisted's Deferreds can't use the stack because they
> implement continuations through callback methods. You
> "addCallback" for the normal case and "addErrback" for the
> exceptions.
>
> It's possible to develop your entire code base this way.
>
> It's going to be structured entirely different than what
> the OP's more senior rule mandator expects, but that might
> be a good thing here.
>
>
>                                Andrew
>                                [hidden email]
>
>
> _______________________________________________
> Baypiggies mailing list
> [hidden email]
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies



--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: Python way to avoid usage of raise

Glen Jarvis
In reply to this post by Nick S Kanakakorn
EXCELLENT NEWS, Nick!!!

Raising is in PEP-8 (http://www.python.org/dev/peps/pep-0008/) and I personally couldn't find a pythonic way to do this otherwise...

Glen

On Wed, Oct 6, 2010 at 2:50 PM, Nick S Kanakakorn <[hidden email]> wrote:
There is a happy news here today.  The use of raise exception is allowed again after I put some coding in using this convention:

exitcode, actual_result = f1()
if exitcode < 0: return exitcode
.... continue something useful with actual_result
exitcode, actual_result = f1()



On Tue, Oct 5, 2010 at 7:15 PM, Nick S Kanakakorn <[hidden email]> wrote:
Hi,

My work place has imposed a rules for no use of exception (catching is allowed).  If I have code like this

def f1()
  if bad_thing_happen():
     raise Exception('bad stuff')
  ...
  return something

I could change it to

def f1()
  if bad_thing_happen():
    return [-1, None]
  ...
  return [0, something]

f1 caller would be like this

def f1_caller():
  code, result = f1(param1)
  if code < 0:
    return code
  actual_work1()
  # call f1 again
  code, result = f1(param2)
  if code < 0:
    return code
  actual_work2()
  ...

Are there more elegant ways than this in Python ?

Thanks,
Nick K




--
-Nick Kanakakorn

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies



--
Whatever you can do or imagine, begin it;
boldness has beauty, magic, and power in it.

-- Goethe

_______________________________________________
Baypiggies mailing list
[hidden email]
To change your subscription options or unsubscribe:
http://mail.python.org/mailman/listinfo/baypiggies
12