简体   繁体   中英

Calling modules from different packages in a python Project

I am trying to wrap my head around the use of the __init__ file in python and I though I did it correctly but I am getting a "No module named ..." error.

I put the project here link to project for simplicity. The issue in question is pythonds/test/parens.py , I have __init__.py files in all my directories so I am not sure where I have gone wrong with this.

I have also tried using PEP 238 using from ..basic.stack import Stack and get the error

ValueError: Attempted relative import in non-package

I though all I had to do was stick an __init__.py files into my directories to make them a module and then I would be able to call them from different modules.

Within the __init__.py file, put:

from myfile import *

for instance:

pythonds/test/parens.py
pythonds/test/__init__.py

Where the __init__.py would contain:

from parens import *

That's the dirty quick-fix version for older python versions. Considering you have multiple subdirectories something along the lines of (see blow) would be better for all python versions:

In your __init__.py in the folder test place:

__all__ = ['tacos','falaffels']
from test.tacos import factory
from test.falaffels import stand

If you have the following folder structure the above should work:

main.py
/test/
    __init__.py
    tacos.py
    falaffels.py

Also just noticed that this might be a duplicate of: How do I write good/correct package __init__.py files

Annoyingly, you elide the actual error: no module named what ? If, as I suspect, it says "no module named 'pythonds', then the problem has nothing to do with __init__.py at all. It is simply that the base pythonds directory is not on your Python path, presumably because you're running the test from within its own directory.

Python automatically puts the current directory in its path: so if ran the test from the pythonds directory you would be able to do from basic.stack import Stack . Otherwise, you could add the full path to the directory above parends to sys.path .

A couple of other tips: you probably already know that the collections module already defines a deque class, and lists can be easily used as stacks already. But more to the point, note that it's not necessary in Python to define a separate file for each class: all three could live in the same stack.py file.

Also, your tests aren't really tests. You should look into the unittest module for how to write proper unit tests in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM