aacanakin
aacanakin

Reputation: 2913

importing from source results in parent module not found while handling absolute import

I have the following folder structure;

app/
ext/
  gredis/
    gredis.py

I have the full path of gredis.py in /Users/blah/blah/blah/ext/gredis/gredis.py

However, when I try to import ext.gredis.gredis module by using;

imp.load_source('ext.gredis.gredis', path)

I have the following error;

RuntimeWarning: Parent module 'ext.gredis' not found while handling absolute import

Do I need to first import ext.gredis ?

NOTE: All folders have __init__.py

Upvotes: 3

Views: 4922

Answers (2)

tddCellar
tddCellar

Reputation: 63

My discovered solution was to assure that the first argument to imp.load_source (i.e. a name for your module) contained no periods. No idea why this matters, but hope it helps someone

Upvotes: 1

Steven Kryskalla
Steven Kryskalla

Reputation: 14659

Can you post the code that reproduces the error? This works for me:

$ tree
.
+-- app
¦   +-- test.py
+-- ext
¦   +-- gredis
¦   ¦   +-- gredis.py
¦   ¦   +-- gredis.pyc
¦   +-- test.py
+-- test.py

$ for path in test.py app/test.py ext/test.py; do python $path; done;
<module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
<module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
<module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>

And test.py contains:

import imp
print(imp.load_source('ext.gredis.gredis', '/tmp/bla/ext/gredis/gredis.py'))

This works in both python 2.x and 3.x.

Upvotes: 3

Related Questions