try exec

Afanasiy abelikov72 at hotmail.com
Fri Jan 17 02:26:15 CET 2003


On Thu, 16 Jan 2003 22:28:05 +0100, Ype Kingma <ykingma at accessforall.nl>
wrote:

>Afanasiy wrote:
>
>> Some code I "exec" throws a TypeError exception. I want it to throw this
>> exception but want to be able to catch this along with the others which
>> are in fact being caught by the try/except block.
>> 
>> The specific TypeError in this case is caused by a module-defined
>> function being called with the incorrect number of arguments. Again,
>> I want to catch this exception. The problem is, this exception, unlike
>> the others, is not being caught/handled by my try/except block.
>
>How do you know it is thrown?

Upon execution of the Python script, the standard exception printout
occurs at this location, denoting exactly what the error is and
halting execution of the script.

  Traceback (most recent call last):
    File "C:\test.py", line 21, in ?
      for line, expecting in lines:
  TypeError: function takes exactly 0 arguments (1 given)

Where, given my code it should have shown (and continued execution) :

  ('Foo() takes exactly 0 arguments (1 given)',)

>The try/except below should catch a TypeError.
>However, I'd prefer to control the namespace in which exec
>is executing. You are not doing this now, so exec executes
>in the namespace it happens to be in, ie. your module's
>namespace. This might cause unexpected results, but
>I would not expect from the code you posted.
>
>Adding namespace gives:
> 

Adding a namespace as you've shown results in the same problem.
At first I was confused by the print repr(namespace) printing
the large text of __builtins__ every loop iteration, but I have
commented that out now. The namespace suggestion is good for
separation, but the TypeError is still not being caught...

HOWEVER, look above, it says the error is on line 21, which is :

  for line, expecting in lines:  

Perhaps I've done something wrong there? (Weird)




More information about the Python-list mailing list