Sven Williamson Sven Williamson - 1 month ago 9
Python Question

Switching between various implementations using module aliasing

I am trying to find a natural mechanism to achieve what looks like 'compile-time' switching between various implementations of the same interface (same 'duck-type').

Suppose I have two classes with some factory functions:

class Number1(object)
...

def fromBytes(byteArray):
...

class Number2(object)
...

def fromBytes(byteArray):
...


defined in
Number1.py
and
Number2.py
respectively, which implements the same functionality. I would like to write client code which start with the following
import
statement:

import Number


where my
Number.py
module is simply a file where the choice of implementation (between say
Number1
and
Number2
is made). I was initially thinking of doing away with
Number.py
and:

import Number1 as Number


in my client code. However, I would like my choice of implementation to be specified in a single location in my project, rather than replicate that choice across several client modules.

I thought of defining
Number.py
as follows:

# choose your implementation here
import Number1
Number = Number1


However, this solution forces me to have my client modules start with:

from Number import Number


which does not look good. I d like to have a simple
import Number
, then call my factory functions as
Number.ZERO
,
Number.fromBytes(...)
for example... What is the pythonic way to do this?

Answer

Using wildcard-import may be easiest way to tackle it.

Number.py:

if use_module_1:
    from Number1 import *
else:
    from Number2 import *

In all client code:

import Number
# or
from Number import some_name

While wildcard import is usually considered a bad practice, that's not a case here, since you actually want to pollute Number namespace with all elements from Number1 or Number2.