Python – ‘import’ or pass modules as parameters?

What you’re talking about is called dependency injection and is considered a good practice for making your code testable. I don’t think there’s anything about Python that would make it unPythonic or a bad practice.

There are other ways you could do it in Python, for example by importing different modules depending on some kind of flag you pass in:

class Foo(object):
    def __init__(self, testing=False):
        if testing:
            import module_test as module
        else:
            import module
        self.module = module

But passing a reference to the module you wish to use is more flexible, separates concerns better, and is no less Pythonic than passing a reference to a class or instance (or string or integer) you wish to use.

For the ordinary (non-test) use case, you can use a default argument value:

class Foo(object):
    def __init__(self, module=None):
        if not module:
            import module
        self.module = module

Leave a Comment