Pycharm warning - 'Relative import outside of a package'

Viewed 804

Here's the working folder structure

foo/
├─ foo/
│  ├─ __init__.py
__main__.py

Here's what __main__.py looks like:

from .foo import bar

bar()

Here's what the __init__.py looks like:

def bar():
    print("hello")
    pass

When I do python -m foo from outside root, it works as expected. However, PyCharm complains about the from .foo import bar line. The warning message is:

Relative import outside of a package

If the problematic line is changed to from foo import bar, PyCharm doesn't complain but I get following error when running python -m foo:

ImportError: cannot import name 'bar' from 'foo' (unknown location)

Is there a way to have it work while resolving PyCharm warnings?

1 Answers

You may be able to get rid of the warnings by turning the top-level foo directory into its own package.

Adding an __init__.py to top-level foo directory might get the job done.

Related