mercredi 16 mars 2016

How to organize imports in a Python class?

Suppose I have a Python class ABC; I want to import some non-default modules into my project, but I'm not sure if the user who runs my code has them installed. To check, I've enclosed my imports in the class inside a try and catch block, as such:

class ABC:
    _canRun = True
    try:
        import XYZ
    except Exception:
        _canRun = False


    def test_function(self):
        if self._canRun:
            import XYZ
            #do stuff using XYZ module
        else:
            print("Cannot do stuff")
            return None

I feel like this is bad design for some reason. Is there a better pattern I can use?

Aucun commentaire:

Enregistrer un commentaire