Why does getattr() exit a program when it raises an exception inside a try statement?

42 Views Asked by At

I have a file called table_builders.py where I have defined multiple classes. Inside another script, I am importing them in a loop. The classes that I am trying to import are listed in builders_list.

Below is how I am doing the import.

import table_builders

for b in builders_list:
    try:
        globals()[b] = getattr(table_builders, b)
        print(f'Successfully imported {b}')
    except ImportError as e:
        print(f'\nError importing {b}. \n{e}')

Not all of the classes in builders_list have been defined in table_builders.py yet. But since I am doing the import inside a try: statement, I would expect the code to import all that have been defined, and skip over the ones that haven't been defined.

What is happening, however, is that the program is exiting as soon as the first import fails. The terminal shows:

Successfully imported CustomersBuilder
Successfully imported FacilitiesBuilder
Traceback (most recent call last):

File ......
    globals()[b] = getattr(table_builders, b)

AttributeError: module 'table_builders' has no attribute 'CustomerFulfillmentPoliciesBuilder'

Note that the print statement inside except never actually prints.

Why is getattr() exiting my program when it throws an error inside of a try: statement?

Is there another way to do the import so that the program doesn't exit when the import fails?

Thank you!

1

There are 1 best solutions below

0
Graham B On

Thank you to those who commented below the original post. I was catching the wrong error (and not actually importing in a loop).