mercredi 21 avril 2021

Try except clauses for importing multiple Python modules

Let's say I have many modules, that may or may not throw some kind of Exception. From each of these modules I'd like to retrieve one class(extending common superclass).

Question

How to neatly avoid writing try except clause which is the same for all of them?

Possible solutions

For example I could write a for loop based on strings representing modules and classes inside them, but this looks bad, e.g. because it loses IDE support.

Another possible solution is to move fail-checking to instance initialization. But failing at import is the first possible place that it can fail, so I guess that's delaying the inevitable.

It would be great if modules could append themselves to some list if they succeed at initializing, but I have no idea how to do that.

Code:

a.py

class A(CommonInterface):
   a = 1 / 0 # simulating bad configuration

b.py

class B(CommonInterface):
   b = 1 # good configuration

all.py

all_classes = []
try:
    from a import A
    all_classes.append(A)
except Exception as e:
    some_common_routine()
try:
    from b import B
    all_classes.append(B)
except Exception as e:
    some_common_routine()

# all_classes == [B]

Aucun commentaire:

Enregistrer un commentaire