Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a virtual package available via sys.modules

Say I have a package "mylibrary".

I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.

I.e., I do:

import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')

Given that setup:

>>> import mylibrary.config    # -> works

>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config

Even stranger:

>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config

So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?

like image 645
miracle2k Avatar asked Dec 15 '08 11:12

miracle2k


2 Answers

You need to monkey-patch the module not only into sys.modules, but also into its parent module:

>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from xml import config as x
>>> x
<module 'xml.config' (built-in)>
like image 58
Martin v. Löwis Avatar answered Oct 01 '22 03:10

Martin v. Löwis


As well as the following:

import sys, types
config = types.ModuleType('config')
sys.modules['mylibrary.config'] = config

You also need to do:

import mylibrary
mylibrary.config = config
like image 21
fuzzyman Avatar answered Oct 01 '22 03:10

fuzzyman