Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import on class instanciation

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.

like image 679
CoMartel Avatar asked Jun 15 '15 11:06

CoMartel


2 Answers

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
like image 101
Vincent Avatar answered Nov 18 '22 10:11

Vincent


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!
like image 3
James Mills Avatar answered Nov 18 '22 12:11

James Mills