Simple python raise statement question

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Inglonias
Posts: 126
Joined: Mon Jun 28, 2010 5:54 pm UTC

Simple python raise statement question

Postby Inglonias » Sat Jul 17, 2010 4:40 pm UTC

Ok, so I built a library for use in my programming course (Not an assignment, so not cheating.)

I have a display_menu function for a console app, and it works fine. I want some help with handling some errors. Here's the function:


The function works, but I have an issue with this part:

Code: Select all

 # Raise an error if any argument isn't a string
   for each_element in menu_list:
      if str(type(each_element)) != "<type 'str'>":
         raise TypeError("Object of type 'str' expected in argument. Got " + str(type(each_element)) + ".")

See, I get this output when someone puts in an integer, which is what I want, but the output doesn't tell the user anything about why HIS code failed.
I'm told I can use three arguments in the raise statement. How would I get it to say that the issue stems from

Code: Select all

print consoleui.display_menu("Six","Seven",1)
instead of the raise statement itself?

Code: Select all

Traceback (most recent call last):
  File "C:\Python26\CS112\Test.py", line 9, in <module>
    main()
  File "C:\Python26\CS112\Test.py", line 4, in main
    print consoleui.display_menu("Six","Seven",1)
  File "C:\Python26\CS112\consoleui.py", line 16, in display_menu
    raise TypeError("Object of type 'str' expected in argument. Got " + str(type(each_element)) + ".")
TypeError: Object of type 'str' expected in argument. Got <type 'int'>.


This tells what raised the error, not what caused it. I want the traceback to point to the user code as the last issue, not the module raise statement! How do I eliminate that?

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: Simple python raise statement question

Postby 0xBADFEED » Sat Jul 17, 2010 5:57 pm UTC

To check for type equivalence relations don't do this:

Code: Select all

str(type(x)) == "<type 'str'>"

Do this:

Code: Select all

type(x) is str
type(x) is not str
type(x) is int
etc....

Ingolnias wrote:I want the traceback to point to the user code as the last issue, not the module raise statement! How do I eliminate that?

No you don't. It's not a good idea to throw away trace information about an error. By keeping the full trace you allow the user to trace all the way to the actual exception that has occurred. If you eliminate the library trace statement the user only has information up to the lib boundary. This can be especially annoying when it's unclear why the actual error occurred.

User avatar
RoadieRich
The Black Hand
Posts: 1037
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Behind you

Re: Simple python raise statement question

Postby RoadieRich » Sat Jul 17, 2010 11:48 pm UTC

0xBADFEED wrote:To check for type equivalence relations don't do this:

Code: Select all

str(type(x)) == "<type 'str'>"

Do this:

Code: Select all

type(x) is str
type(x) is not str
type(x) is int
etc....

That's just as bad. You want to use

Code: Select all

isinstance(x, str)


Example of why:

Code: Select all

class MyStr(str):
    def dummyExtraMethod(self):
        pass

#There is no reason NOT to accept MyStr anywhere code expects a vanilla str.  But:
x = MyStr("Hello World")
print type(x) is str #prints False
print isinstance(x, str) #prints True


It's also easy to add in unicode support:

Code: Select all

isintance(x, (str,unicode)) #isinstance can accept an iterable of types
#or
isinstance(x, basestring) #basestring is an uninstanceable common parent to str and unicode
73, de KE8BSL loc EN26.

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: Simple python raise statement question

Postby 0xBADFEED » Sun Jul 18, 2010 12:03 am UTC

RoadieRich wrote:That's just as bad. You want to use

Code: Select all

isinstance(x, str)

...

Except that doesn't do the same thing at all. I was just trying to show the appropriate way to test equivalence between types (and preserve the semantics of his code). Whether he really wants equivalence or not is a separate matter and debatable.

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Simple python raise statement question

Postby phlip » Mon Jul 19, 2010 3:13 am UTC

To answer the OP's actual question: after some massaging, Google finds this.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

jagdragon
Posts: 19
Joined: Sat Feb 28, 2009 11:35 pm UTC

Re: Simple python raise statement question

Postby jagdragon » Mon Jul 19, 2010 3:39 am UTC

Code: Select all

type(x) is str
type(x) is not str
type(x) is int
etc....


The more correct way to do that is this:

Code: Select all

type(x) == type(str)
type(x) == type("")
type(x) == type("foo")

etc.

User avatar
RoadieRich
The Black Hand
Posts: 1037
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Behind you

Re: Simple python raise statement question

Postby RoadieRich » Mon Jul 19, 2010 10:16 am UTC

Did you even try that?

Code: Select all

>>> x = "Hello World"
>>> type(x) is str
True
>>> type(x) is not str
False
>>> type(x) is int
False
>>> type(x) == type(str)
False
>>> type(x) == type("")
True
>>> type(x) == type("foo")
True

How are those two snippets of code even remotely equivalent? Don't even get me started on the extra function calls that you don't need.
73, de KE8BSL loc EN26.

jagdragon
Posts: 19
Joined: Sat Feb 28, 2009 11:35 pm UTC

Re: Simple python raise statement question

Postby jagdragon » Fri Jul 23, 2010 8:25 am UTC

Whoops, sorry, got mixed up between programming languages. Also I left out the brackets: type(str) should have been type(str())


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 4 guests