Sven Williamson Sven Williamson - 1 year ago 84
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
respectively, which implements the same functionality. I would like to write client code which start with the following

import Number

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

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
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
for example... What is the pythonic way to do this?

Answer Source

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

if use_module_1:
    from Number1 import *
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download