Python 2.7: Dynamic module import in an imported module based on given variable -


there given 2 versions of storage. based on version, need select proper interface module result.

the file structure looks this:

lib/     __init__.py     provider.py     connection.py     device.py      storage/         __init__.py         interface_v1.py    # interface storage of version 1         interface_v2.py    # interface storage of version 2  main.py 

the main.py imports provider.py, should import 1 of interfaces listed in storage subpackage depending on version of storage.

main.py:

from lib.provider import provider lib.connection import connection lib.device import device  connection = connection.establish(device) storage_version = device.get_storage_version()  massage = provider.get_data(connection) 

provider.py should import interface storage based on storage_version , implement provide functions:

from storage import interface  class provider(object):      def __init_(self):         self.storage = interface.storage      def get_data(self, connection):         return self.storage.get_data()      def clear_storage(self, connection):         self.storage.clear_storage() 

this example not complete, should sufficient problem explanation.

additional question:

  • is possible use storage.__init__ use import subpackage?
  • how proper implement factory in python?

assuming interface_v1 , interface_v2 bith impleement class storageclassi guess this:

import storage.interface_v1 import storage.interface_v2  class provider(object):      def __init__(self , version):         if version == 1:            self.storage = storage.interface_v1.storageclass         else:            self.storage = storage.interface_v2.storageclass 

would best solution - https://docs.python.org/2/library/functions.html#import should provide way import module based on name.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -