Abhishek Divekar
Abhishek Divekar

Reputation: 1267

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?

Upvotes: 0

Views: 505

Answers (1)

vz0
vz0

Reputation: 32933

imports are usually placed at the start of the py file:

try:
    import XYZ
except ImportError:
    XYZ = None

class ABC:
    def test_function(self):
        if XYZ is None:
            raise Exception("Cannot do stuff")

However the try/except ImportError trick is usually done when you can pick an alternative:

try:
    import XYZ
except ImportError:
    import ZZTop as XYZ # if ZZTop fails, all fails. And that's fine.

class ABC:
    def test_function(self):
        XYZ.something()

Otherwise it is advisable to just fail as easly as possible:

import XYZ

class ABC:
    def test_function(self):
        XYZ.something()

Upvotes: 1

Related Questions