1

I have the following directory layout:

A/
  A1.py
  B/ 
    B1.py

And B1.py is a script that relies on A1.py. My understanding is that if A has an __init__.py, then in B1.py I should be able to say:

from A import A1

However, no matter what I do I seem to get an ImportError: Module A not found. One of the things I've tried is doing

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

But this doesn't seem to have helped either, and anyway it seems strange to me that such an ad hoc method is the solution.

I'm using python 3.5.1 Also, one other thing I guess I should double check - is it ok to have non-'.py' files within a module?

I'm at my wits' end about this - I've looked it up and it seems to me that this setup should work, but I suppose there's something I'm just not understanding. I'm sorry for making a more or less duplicate question to many that have been seen before, but it seems to me that I've followed the instructions given in other answers and it still isn't working.

As a side note - why is this not really easy in python? Why can't I just say something like

import ../A1

Any advice or comment is greatly appreciated.

ira
  • 735
  • 1
  • 7
  • 12
  • Have you tried `from .. import A1`? See [PEP 328](https://www.python.org/dev/peps/pep-0328/) for more details. – rmunn Apr 18 '16 at 01:10
  • Yes I've tried this - I get SystemError: Parent module '' not loaded, cannot perform relative import – ira Apr 18 '16 at 01:11
  • Where exactly are you running your python command from? – idjaw Apr 18 '16 at 01:14
  • I do know a way of getting the file but I am having trouble recalling it. I think it was one of the os functions. – SMS von der Tann Apr 18 '16 at 01:15
  • I'm running "> python3 B1.py" from within B – ira Apr 18 '16 at 01:16
  • @ira Typically I always pick a single point of execution for my code to avoid complications with imports. So, I will always have a main.py (or similarly named) in the root of my package (A in your case), and I will make sure all my imports are with respect to that point. – idjaw Apr 18 '16 at 01:26
  • Also, to provide you with more details on the error messages you are getting, read [this](https://www.python.org/dev/peps/pep-0366/) and [this](http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py). [This](http://stackoverflow.com/questions/4348452/python-packaging-for-relative-imports). Also, [this](http://stackoverflow.com/questions/4348452/python-packaging-for-relative-imports) – idjaw Apr 18 '16 at 01:26

1 Answers1

0

You need to install your module. Do a pip install . from A's directory. Then from B, do from A import ... The fact that A has an __init__ tells me it is intended to be a library. You need a setup.py file in A's dir as well.

Tommy
  • 12,588
  • 14
  • 59
  • 110