volvox
volvox

Reputation: 3060

PyDev not seeing self-written Python 3 package

Right this is starting to get frustrating. I've read the manual on imports and googled around and I'm obviously missing something.

I have:

mypkg/

mypkg/__init__.py
from .primitives import circle

mypkg/primitives/__init__.py
from .circle import vecCircle

mypkg/primitives/circle.py

In Project>Properties>PyDev>PYTHONPATH I have added /path/to/mypkg In my .bash_profile I appended /path/to/mypkg to PYTHONPATH and exported. I know I don't need both, but removing one or the other has no effect on the below.

In PyDev, I then want to do a

import mypkg
c = vecCircle(args)

but at the moment vecCircle is underlined red (undefined variable)

I try

import mypkg.primitives
c = vecCircle(args)

or

import mypkg.primitives
c = circle.vecCircle(args)

or

 import mypkg.primitives.circle
 c = circle.vecCircle(args)

and the only thing that changes is circle of circle.vecCircle underlines in red with the same error. How can I get what I want?

I'm getting

Unused import: mypkg
Unresolved import: 
 mypkg
 Found at: mypkg.__init__

Upvotes: 0

Views: 53

Answers (2)

Blckknght
Blckknght

Reputation: 104832

Importing a module doesn't put all of its contents into your namespace (unless you use from module import *). Your code is just importing the module. I think the imports in the __init__.py files may have confused you. They import names from deeper in the package into their own namespaces, but have no effect on any namespace that imports them.

You can fix this in two ways.

The simplest approach is probably to use attribute syntax to get to the vecCircle value you're trying to access:

import mypkg

mypkg.circle.vecCircle(args)

If you really want to be able to access vecCircle directly in your own namespace, you can change the import around using from module import name syntax:

from mypkg.circle import vecCircle

vecCircle(args)

For both of those solutions, I've been using the shorter name mypkg.circle.vecCircle for the object that was originally created as mypkg.primitives.circle.vecCircle. The import you're doing in mypkg/__init__.py enables this. You could instead use mypkg.primitives.vecCircle if you prefer that (using a different short name, enabled by the import in mypkg/primitives/__init__.py).

Upvotes: 2

cg909
cg909

Reputation: 2556

Python searches directories in PYTHONPATH for a subdirectory with the name of the module to import.

So you need to add the parent directory of /path/to/mypkg to your PYTHONPATH, not /path/to/mypkg itself.

Upvotes: 0

Related Questions