I am running PyCharm 2019.2.5 with a toy example. I have the following directory structure:
├── main.py
├── a_package
│ ├── a_module.py
My a_module.py
file looks like this:
class a_class:
def __init__(self):
self.a_variable = 5
And my main.py
file looks like this:
from a_package import a_module
x = a_module.a_class()
print(x.a_variable)
Running main.py
outputs 5
. This is as expected. However, I have a couple of questions about all of this.
1) In main.py
, in the line from a_package import a_module
, both a_package
and a_module
have a red line underneath in PyCharm. Hovering over this reveals "Unresolved reference 'a_package'" and "Unresolved reference 'a_module'". Why is this happening? PyCharm is clearly able to find these files, since the code runs ok.
I have also tried adding the directory a_package
to the "Sources" in "Settings -> Project -> Project Structure". However, this does not affect anything. PyCharm still gives me a message saying that it cannot find these references. According to the PyCharm documentation on the source roots, "These roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports." So, even after adding this directory to the source root, it is strange that it is giving me this error / warning. Why is this happening?
2) I often see a similar structure to the above, but with an empty __init__
file as follows:
├── main.py
├── a_package
│ ├── __init__.py
│ ├── a_module.py
My understanding is that this makes a_package
an actual Python package, whereas before it is just a directory containing Python files. But why would this be done? Why can I not just have it as I originally had it, without the __init__
file, and just import the module as I did above?