0

The Python Zen says:

There should be one-- and preferably only one --obvious way to do it

What's the right way to import another file from the same folder in Python 2.7

.
└── myfolder
    ├── file1.py
    ├── file2.py
    └── __init__.py

(Assuming __init__.py is empty)

Solution 1:

file2.py should contain

from myfolder import file1

this works fine: python -m myfolder/file2

However, this approach requires naming myfolder everywhere (which seems silly: you shouldn't have to refer to your family members by their last names and cities of origin)

Solution 2:

On the other hand, this fails with "ValueError: Attempted relative import in non-package":

from . import file1

Solution 3:

as does this:

from __future__ import absolute_import
from . import file1

Solution 4:

And this version fails with "No module named file1":

import file1

Solution 5:

Putting every file in its own folder with __init__.py next to it also doesn't seem like a very sane approach.

MWB
  • 11,740
  • 6
  • 46
  • 91
  • To what you think seems silly: explicit is better than implicit. – jonrsharpe Mar 26 '17 at 21:19
  • @jonrsharpe `from .` is even more explicit, and doesn't need to be changed when packages get renamed, yet it doesn't work. – MWB Mar 26 '17 at 21:22
  • It works *within* a package. If you have dependencies *between* packages, they should be resolved by the name of the package rather than just where it happens to be. If that other package gets renamed, isn't it *right* that the reference also changes in other packages that use it? – jonrsharpe Mar 26 '17 at 21:24
  • @jonrsharpe myfolder is a package; file2 is in it; relative import doesn't work *within* myfolder. Am I misunderstanding you? – MWB Mar 26 '17 at 21:28
  • Sorry, you're right; the problem is the way you're *running* it. It's because you're trying to run `file2.py` directly, rather than from outside `myfolder`. See e.g. http://stackoverflow.com/q/14664313/3001761 – jonrsharpe Mar 26 '17 at 21:30
  • @jonrsharpe Nope: I'm running it as `python -m myfolder/file2`, outside myfolder (It's in the question) – MWB Mar 26 '17 at 21:32

1 Answers1

2

Three things:

  • __init__.py in myfolder

  • in file2.py:

    from .file1 import *
    

    or

    from . import file1
    
  • python -m myfolder.file2 (note the . and not the /)

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Eric
  • 4,821
  • 6
  • 33
  • 60