adapap
adapap

Reputation: 665

Importing modules from subdirectories

I have a file structure like this:

package/
  __init__.py
  foo.py
  subdir/
    bar.py
    baz.py

I want to be able to run foo.py and import bar.py. Inside bar.py, baz.py is imported using import baz. The problem is that bar is not able to import baz if I import it into foo.

foo.py

from importlib import import_module
import_module('subdir.bar', package='package')

Upvotes: 1

Views: 87

Answers (1)

admirableadmin
admirableadmin

Reputation: 2759

You also need a __init__.py inside your subdir folder. See the example below and the output:

foo.py

from subdir import bar
print "hello from foo.py"

subdir/__init__.py

(empty)

subdir/bar.py

import baz
print "hello from bar.py"

subdir/baz.py

print "hello from baz.py"

output of running foo.py

hello from baz.py
hello from bar.py
hello from foo.py

Upvotes: 1

Related Questions