6

I'm creating a module with several classes in it. My problem is that some of these classes need to import very specific modules that needs to be manually compiled or need specific hardware to work.

There is no interest in importing every specific module up front, and as some modules need specific hardware to work, it could even raise errors.

I would like to know if it is possible to import these module only when needed, that is on instantiation of a precise class, like so :

class SpecificClassThatNeedRandomModule(object):
    import randomModule

Also I am not sure that this would be a good pythonic way of doing the trick, so I'm open to suggestion for a proper way.

James Mills
  • 18,669
  • 3
  • 49
  • 62
CoMartel
  • 3,521
  • 4
  • 25
  • 48
  • 3
    I don't think putting the import statement in a class definition will delay it like you expect. However, you can do your import in a function and then it will only be happen the first time that function is invoked. – Vaibhav Sagar Jun 15 '15 at 11:39
  • 2
    Also check [how to test if one python module has been imported?](http://stackoverflow.com/questions/5027352/how-to-test-if-one-python-module-has-been-imported) . Good things exists on tha posts. – Mp0int Jun 15 '15 at 11:47

2 Answers2

4

It is possible to import a module at instantiation:

class SpecificClassThatNeedRandomModule(object):
    def __init__(self):
        import randomModule
        self.random = randomModule.Random()

However, this is a bad practice because it makes it hard to know when the import is done. You might want to modify your module so that it doesn't raise an exception, or catch the ImportError:

try:
    import randomModule
except ImportError:
    randomModule = None
Vincent
  • 12,919
  • 1
  • 42
  • 64
  • Whilst this *may* be poor practice; I believe the OP is trying to only import modules that are actually needed or used per se. But +1 on the "good practice". – James Mills Jun 15 '15 at 11:46
  • @PadraicCunningham You couldn't. You'd have to do: ``if randomModule:`` – James Mills Jun 15 '15 at 12:26
3

You'll want to "import" in the constructor of your class:

Example:

class SpecificClassThatNeedRandomModule(object):

    def __init__(self, *args, **kwargs):
        import randomModule

        self.randomModule = randomModule  # So other methods can reference the module!
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • 1
    You are right, but you need to add `self.randomModule=randomModule` if you want to use your module in other function of the instance. Thanks anyway for your answer! – CoMartel Jun 15 '15 at 14:33