3

I want to import main_file.py from sub_file.py, i have my init files setup. I am able to do in my main_file.py:

from sub_folder.sub_file import * 

However i do not know how to do it the other way around.

This is my structure:

|+main_folder
|--_init_.py
|--main_file.py
|++sub_folder
|---_init_.py
|---sub_file.py
6
  • Use underscore (_) instead of - then import main_folder.main_file Commented Apr 21, 2017 at 16:46
  • 1
    You might be interested in this The Anatomy of a Python Project. It's possible to do a editable install of your code to make it available like a package. Commented Apr 21, 2017 at 16:46
  • its just sudo code but i tried it but it does not seem to work Commented Apr 21, 2017 at 16:47
  • @e_man106, how are you running your script? Commented Apr 21, 2017 at 16:49
  • @e_man106, is sub_folder insdie main_folder? Commented Apr 21, 2017 at 16:51

1 Answer 1

3

The old way:

  • Make sure the directory with main_folder is on your sys.path;
  • from main_folder import main_file.

The new, usually better way:

  • from ..main_folder import main_file

This has the advantage of never clashing with system imports. If you rename your main_folder to e.g. math, from math import my_func will crash, because stdlib's math does not have this function, or import from your module, depending on sys.path. OTOH from ..math import my_func will definitely always import from your own module.

If in doubt, always print sys.path before your failing import statement to understand if you're actually looking at the right directories.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.