How to reference python package when filename contains a period

Alexander Bird picture Alexander Bird · Dec 1, 2009 · Viewed 26.8k times · Source

I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:

from "models.admin" import *

however, I get a syntax error for having double quotes. But if I just do

from models.admin import *

then I get "ImportError: No module named admin"

Is there any way to import from a python file that has a period in its name?

Answer

Cat Plus Plus picture Cat Plus Plus · Dec 1, 2009

Actually, you can import a module with an invalid name. But you'll need to use imp for that, e.g. assuming file is named models.admin.py, you could do

import imp
with open('models.admin.py', 'rb') as fp:
    models_admin = imp.load_module(
        'models_admin', fp, 'models.admin.py',
        ('.py', 'rb', imp.PY_SOURCE)
    )

But read the docs on imp.find_module and imp.load_module before you start using it.