1

I understand from Chris Yeh's helpful guide that the dot implies "in this directory" relative to the specific module that I'm running. But given this project:

project/
--main.py
--lib/
​   --bar.py
​   --foo.py

bar.py:

class Ball:
    pass

foo.py:

from .bar import Ball


class SoccerBall(Ball):
    pass

main.py:

from lib.foo import SoccerBall

s = SoccerBall()

Running main.py works as expected.

However, if I want to run foo.py, I need to remove the dot from the import statement (something my IDE marks as an error):

from bar import Ball

I would expect the dot to be needed when I run foo.py, and for main.py to require the import as from .lib.bar import Ball. What am I missing?

print(sys.version)
> 3.7.4 (default, Aug 13 2019, 15:17:50)
Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
  • Instead of you running it as a file, run it as a module? `python3 -m lib.foo` This answer is defined as solution 1 from @a_guest and is ideal if you are trying to fun files from within a module with dependancies across other files. – Fallenreaper Mar 11 '20 at 13:52
  • OK. It was mainly a theoretical question. My understanding is that if you run a file as `__main__`, it will not use relative imports, so you find the adjacent folder directly (without dots). If you're importing it from somewhere else, it's run as a module, so relative imports work - thus you need the dot. The IDE (PyCharm) sees that it's in a directory below top-level, so assumes it should have a dot. Thanks! – Josh Friedlander Mar 11 '20 at 14:55

0 Answers0