0

I have a set of Python scripts that interact. I call my "main" script from the parent directory (parent/main.py), which imports function from a script foo in a subdirectory (parent/child/foo.py), which in turn imports functions from another program bar (parent/child/bar.py). I'm getting a ModuleNotFoundError for bar.py when I try to run main.py.

I read into namespace modules and as best I can tell, I'm not doing anything wrong as apparently "from child.foo import myfunc" should be fine?

Stack trace, per request:

Traceback (most recent call last):
  File ".\main.py", line 2, in <module>
    import child.foo
  File "C:\biglongpath\parent\child\run_n1.py", line 1, in <module>
    from bar import myfunc as mf
ModuleNotFoundError: No module named 'bar'
3
  • you don't have to include the .py in child.foo.py Commented Jan 22, 2021 at 0:39
  • Can you add A) the import code that's blowing up and B) the stacktrace to your description? Commented Jan 22, 2021 at 0:40
  • @MitchellOlislagers Oops, I don't have that in the actual -- typo. Apologies. Commented Jan 22, 2021 at 0:40

1 Answer 1

2

In Python 3.x you need to write:

from child.foo import myfunc

In Python 2.7:

You should include an __init__.py file (even if it is empty) in each child directory.

Sign up to request clarification or add additional context in comments.

3 Comments

This worked (3.x) -- thanks. Can you offer an explanation as to how it works? My guess would've just been that imports "copy" the code over so everything needs to be in terms of the outermost but I have no idea how accurate that is. Also to clarify for others -- this is for bar (e.g. should be child.bar)
@LiamWilson import is syntactic sugar for the __import__ func (read more in the docs here). The simplest answer is that is the way that it is implemented in the standard library (I know, not very satisfying). But basically when you run python on a .py file, python first parses the file, make imports, makes space for variables declared, and gives some basic checks to ensure that you are being consistent with spaces/tabs, etc. Part of that process is loading the modules that you request. But, it must be in the format __import__ expects :)
Ah, got it. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.