Karnivaurus
Karnivaurus

Reputation: 24151

PyCharm gives "unresolved reference" message, but can run the code

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?

Upvotes: 1

Views: 1206

Answers (2)

luk_dev
luk_dev

Reputation: 164

This is an issue with PyCharm, not with python itself, that's why you're able to run it. Select the root folder of your sources (presumably src), right-click and select Mark Directory As -> Sources Root.

Upvotes: 1

Coding Cow
Coding Cow

Reputation: 81

1) When PyCharm's warnings bug (although it is not frequent), you can fix it by cuting the code and then pasting it. You can also try to restart PyCharm.

2)

My understanding is that this makes a_package an actual Python package, whereas before it is just a directory containing Python files

I agree with you on this point.

I am able to import modules without a __init__ file so you should be able to as well.

Upvotes: 1

Related Questions