简体   繁体   中英

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

There are given two versions of a storage. Based on the version, I need to select the proper interface module to get the result.

The file structure looks like this:

lib/
    __init__.py
    provider.py
    connection.py
    device.py

    storage/
        __init__.py
        interface_v1.py    # interface for storage of version 1
        interface_v2.py    # interface for storage of version 2

main.py

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

main.py:

from lib.provider import Provider
from lib.connection import Connection
from lib.device import Device

connection = Connection.establish(Device)
storage_version = Device.get_storage_version()

massage = Provider.get_data(connection)

provider.py should import an interface to the storage based on storage_version and implement provide some 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 is not complete, but should be sufficient for the problem explanation.

Additional question:

  • Is it possible to use storage.__init__ to use import just the subpackage?
  • How to proper implement Factory in Python?

Assuming the interface_v1 and interface_v2 bith impleement a class StorageClass I guess something like 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 be the best solution - but https://docs.python.org/2/library/functions.html# import should provide a way to import a module based on name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM