iero
iero

Reputation: 411

Python project structure : "Unresolved reference"

I structured my python project like that:

- project/
+- package/
 +- db/
  +- __init__.py
  +- mydb.py
+- tests/
 +- context.py
 +- mytest.py
+- file.py

In project/package/db/__init__.py I declared mydb as :

from package.db import mydb

With this declaration, I can use mydb functions in file.py, using:

import package.db as db

db.mydb.myfunction()

But I would like to use this function in project/tests directory as well. So, I added a project/tests/context.py file with:

import os
import sys

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import package.db as db

And in mytest.py :

from context import db

db.mydb.myfunction()

It's working well.

But PyChar says that :

Is there a way to improve this project structure in order to get rid of those warning & errors ?

Thanks

Upvotes: 2

Views: 812

Answers (1)

Julian Camilleri
Julian Camilleri

Reputation: 3105

  1. You don't have an __init__.py file in your package and tests folders; meaning it's not a python package. - If you want them to be.

  2. You're not using the import statement properly; also, you're not using the import in the context.py file, so in order to fix it, you'll need to remove the line.

  3. I suggest reading more here about packages; which will give you more insight into what you should put inside your __init__.py files.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

The structure I would use:

- package_name
   - db
     - __init__.py
     - my_db.py
   - tests
     - __init__.py
     - my_test.py
   - __init__.py

The only code you need to add is in the my_db.py file:

def my_function():
    return 1

and in your my_test.py file you'll have:

from package.db import mydb

mydb.my_function()

That's all you need; in regards to altering imports through the __init__.py file, look into __all__ if you really have to.

Upvotes: 1

Related Questions