Import on class instanciation
Question: 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.


Answer: 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
    

