Search code examples
pythonpython-3.xpython-3.4

Pass-through/export whole third party module (using __all__?)


I have a module that wraps another module to insert some shim logic in some functions. The wrapped module uses a settings module mod.settings which I want to expose, but I don't want the users to import it from there, in case I would like to shim something there as well in the future. I want them to import wrapmod.settings.

Importing the module and exporting it works, but is a bit verbose on the client side. It results in having to write settings.thing instead of just thing.

I want the users to be able to do from wrapmod.settings import * and get the same results as if they did from mod.settings import * but right now, only from wrapmod import settings is available. How to I work around this?


Solution

  • If I understand the situation correctly, you're writing a module wrapmod that is intended to transform parts of an existing package mod. The specific part you're transforming is the submodule mod.settings. You've imported the settings module and made your changes to it, but even though it is available as wrapmod.settings, you can't use that module name in an from ... import ... statement.

    I think the best way to fix that is to insert the modified module into sys.modules under the new dotted name. This makes Python accept that name as valid even though wrapmod isn't really a package.

    So wrapmod would look something like:

    import sys
    
    from mod import settings
    
    # modify settings here
    
    sys.modules['wrapmod.settings'] = settings   # add this line!