3

I've got a simple python package with the following directory structure:

wibble
|
|-----foo
|      |----ping.py
|
|-----bar
|      |----pong.py

Simple question: How would I reference a function / class in ping.py from pong.py? Looking through the documentation, this appears to be as simple as creating __init__.py files in the root of wibble, foo and bar and then from pong.py doing something like from wibble.foo.ping import important_function. However, trying this leads to No module named wibble.foo.ping.

I'm sure I've missed something in the documentation somewhere, because this must be possible to do. I'm also a little hazy on the differentiation between a module and a namespace, my background is c#.net, so any analogies here will be useful.

1 Answer 1

3

you need to add wibble to python path (see the official documentation), one way is

import sys
sys.path.append('/path/to/wibble')

Another way is with the environment variable PYTHONPATH

export PYTHONPATH=$PYTHONPATH:/path/to/wibble
Sign up to request clarification or add additional context in comments.

5 Comments

On Windows, so it would be PATH=%PATH%;c:\path\to\wibble (Just guessing because of c#.net reference.)
I should have said - this is being developed on *nix. My concern about this solution is that it hard-ties the absolute location of the package to the codebase / infrastructure. Given that these files are easily locatable relative to each other, why can't pong know that it's in the wibble package and then locate ping that way?
You can dinamicly guess the location of pong.py file and add the wibble folder to python path, but definetly that is a bad practice
if you use something like setup.py for your package the code will worok, but the issue here is: your folder wibble is not in the python path.
I agree that guesswork is bad practice. I'll try the sys.path.append approach on both ping and pong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.