سؤال

I have APIs [port.py] with the same interface for two different hardware platforms: mips and powerpc. By the same interface I mean that classes are the same, thier methods are the same, but implementation differs.

mips/port.py
powerpc/port.py

A program that uses these APIs should be decoupled from the specific platform and the code looks exactly the same except importing packages. How is it possible to dynamically select the platform, something like the code below, where platform is a global setting (mips or powerpc) or whatever like this:

from [platform].port import PortCli

I tried importing with if, but it looks nasty and doesn't scale well since I may need to add a different platform.

Thank you

Update after discussion with Eduard:

The code below is actually an analogue of import mips.port:

import importlib
platform = 'mips'
myModule = importlib.import_module(platform + '.port')
myModule.Port().PrintMe()

It's fine, but I need to add myModule everywhere. Is it possible to have a similar substitute for from mips.port import Port?

هل كانت مفيدة؟

المحلول

Based on post of Python Core Developer Andrey Svetlov.

I can suggest you to add platform/hardware specific Python modules in separate directories and append this modules to sys.path in runtime.

For example: We have a package

  • package
    • __init__.py
    • a.py
    • x86_64
      • b.py
    • i386
      • b.py

__init__.py will contain something like this:

import sys
import platform
from os.path import join, dirname
__path__.append(join(dirname(__file__), platform.machine()))

With this approach common code is located in package while platform specific distributed in subdirectories.

Take attention that x86_64 and i368 do not have __init__.py module.

Import required module b

from package import b
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top