4

I have a directory structure as follow:

evaluate.py
tools (folder)
   -- ngram.py
   -- bleu.py

In bleu.py, I import ngram. And, in evaluate.py, I import tools.bleu. However, an error occurs that ModuleNotFoundError: No module named 'ngram'. Where did I do wrong? Thanks~

Steve Yang
  • 225
  • 2
  • 9
  • You say you made `ngram.py` and tried to import it, but it looks like you tried to import `gram`, not `ngram`, at least according to your error message. Typo? – ShadowRanger Dec 20 '18 at 03:26
  • 1
    can u rewrite your question by mentioning tree structure of directories. As like this question https://stackoverflow.com/questions/53760098/python-include-library-folder-when-running-from-command-line/53760336#53760336 – Saiful Azad Dec 20 '18 at 03:27
  • @ShadowRanger Sorry, typo – Steve Yang Dec 20 '18 at 03:31

1 Answers1

6

If you intend for tools to be a package, you'll need to change the modules within it to use either absolute imports or explicit relative imports when they are importing each other.

That is, you need to change tools/bleu.py to do either:

import tools.ngram     # or: from tools import ngram

Or:

from . import ngram

You should probably put an __init__.py file in the tools folder too (though it's not strictly necessary any more).

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • It works, thanks! What if I only want to import one function, say `get_ngram` from the `ngram.py` file? – Steve Yang Dec 20 '18 at 04:02
  • 2
    I think you can use `from .ngram import get_ngram` for that. Note the dot preceeding the module name, which tells Python it's a relative import. – Blckknght Dec 20 '18 at 04:33
  • Just a note, while going for the complexities, just make sure you don't run into circular dependencies. – 0xInfection Dec 20 '18 at 06:43