1

I have a file structure like

math/
    snippets/
        numerical_methods.py
    homework1/
        main.py
    homework2/
        main.py

And in homework 1's main.py, I would like to do

from ..snippets.numerical_methods import fixed-point-iteration

So that I do not have to re-write this algorithm for every assignment I use it in. But I'm getting the error "Parent module '' not loaded, cannot perform relative import". What am I doing wrong?

nupanick
  • 754
  • 8
  • 13

1 Answers1

3

You can't import from something higher up in the hierarchy than your main script, i.e. something higher up than the homework1 folder. What you can do is add the path to the script you want to the import path:

import sys
sys.path.append("..")
from snippets.numerical_methods import fixed-point-iteration
Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 2
    *You can't import from something higher up in the hierarchy than your script* - Actually you can... – vaultah May 11 '15 at 12:38
  • 1
    See examples from [this](https://docs.python.org/3.4/tutorial/modules.html#intra-package-references) page ("Intra-package References" section) – vaultah May 11 '15 at 12:44
  • 2
    Ease up on the downvotes folks. You can't import higher up than your *main* script. From the link: "Note that relative imports are based on the name of the current module. Since the name of the main module is always "`__main__`", modules intended for use as the main module of a Python application must always use absolute imports." I edited the answer to make that clearer. – Claudiu May 11 '15 at 13:19