Import by class instanciation

I am creating a module with several classes in it. My problem is that some of these classes need to import very specific modules that need to be compiled manually or to use certain equipment.

There is no interest in importing each particular module from the front, and since some modules require certain equipment to work, it can even cause errors.

I would like to know if this module can be imported only if necessary, that is, when creating the exact class, for example:

class SpecificClassThatNeedRandomModule(object): import randomModule 

Also, I'm not sure if this would be a good pythonic way to do the trick, so I am open to suggestions for the right path.

+6
source share
2 answers

You can import the module when creating the instance:

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

However, this is bad practice because it is difficult to understand when the import is completed. You might want to change your module so that it does not throw an exception, or catch an ImportError :

 try: import randomModule except ImportError: randomModule = None 
+4
source

You need 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! 
+3
source

Source: https://habr.com/ru/post/989127/


All Articles