0

I understand that there are (at least) two ways I can do imports.

Assuming that FooMod is in a sibling directory to the directory I'm currently in and assuming that pathToFooMod is a relative path, not an absolute path:

sys.path.append(pathToFooMod)
import FooMod

or

import ../FooMod

Both will work (for some circumstances). Given the situation that either solution would work (with or without modifications), what's the reason to use one or the other?

The second is technically a bit cleaner, but not by much and package imports aren't really a commonly-inspected area of the code anyway.

Both will fail if FooMod gets moved, so there's no maintenance/stability difference that I see.

I found plenty of questions asking how to do one or the other, or how to switch from one to other, but not why. Is the only reason to use one over the other in situations where one method simply doesn't work?

Thanks in advance.

JuniorIncanter
  • 1,569
  • 2
  • 16
  • 27
  • is `import ../FooMod` a syntax error? – Aaron Apr 01 '21 at 20:29
  • `import ../FooMod` is not valid Python code. As far as I know, only the first method actually works. – Tim Roberts Apr 01 '21 at 20:30
  • You presumably mean something like `import ..sibling_folder.FooMod`. – Karl Knechtel Apr 01 '21 at 20:31
  • As you already said the second method is cleaner (but the slash is a typo) and should be used where possible because (1) another module with the same name could maybe found and accidentally imported through the path list and (2) other parts of the code may rely on the state of the path list (e. g. if they themselves add and remove parts of it). – Michael Butscher Apr 01 '21 at 20:35

0 Answers0