[Python-ideas] Arguments to exceptions

Terry Reedy tjreedy at udel.edu
Tue Jul 4 17:40:39 EDT 2017


On 7/4/2017 3:32 PM, David Mertz wrote:
> I don't see the usefulness rich exception data as at all as limited as 
> this. Here's some toy code that shows a use:
> 
> 
> ----
> 
> # For some reason, imports might not be ready immediately
> # Maybe flaky network drive, maybe need to install modules, etc
> # The overall program can do things too make them available
> lazy_import("foo", "bar", "baz", "blat")
> 
> while True:
>      try:
>          x = foo(1) * bar(2) + baz(3)**blat(4)
>          break
>      except NameError as err:
>          lazy_import(err.name <http://err.name>)
>          sleep(1)

Alternate proposal: give the NameError class a .name instance method 
that extracts the name from the message.  This should not increase the 
time to create an instance.  You would then write 'err.name()' instead 
of 'err.name'. For 3.6

def name(self):
     msg = self.args[0]
     return msg[6:msg.rindex("'")]

# current test

try: xyz
except NameError as e:
     print(name(e) == 'xyz')

# Exceptions unittest to ensure that the method
# stays synchronized with future versions of instances

def test_nameerror_name(self):
     try:
         xyz
     except NameError as e:
         self.assertEqual(e.name(), 'xyz')

Generalize to other exceptions.

Further only-partially baked idea: Since exceptions are (in cpython) 
coded in C, I wonder if C data could be inexpensively attached to the 
instance to be retrieved and converted to python objects by methods when 
needed.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list