10

I'm new to python and I don't know how to organize the project structure in the right way, so all auto imports would work in pycharm.

That's my current structure.

enter image description here

In PublisherSubscriberTest pycharm generated this import

from Rabbit.RabbitReceiver import RabbitReceiver
from Rabbit.RabbitSender import RabbitSender

But it's not working. That's the output.

ImportError: No module named Rabbit.RabbitReceiver

What have I done wrong?

I'm more familiar with java. And for example in java I would just create package with some classes and then I would be able to import them anywhere in my project. AFAIK it's not the same with python somehow.

Could someone explain this to me?

EDIT1: Yes, I know about sys.path.append. I used to do it that way, but It seemed strange to me and i want to be able to do it without it.

user1685095
  • 5,787
  • 9
  • 51
  • 100

1 Answers1

2
import sys, os.path

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from Rabbit.RabbitReceiver import RabbitReceiver
from Rabbit.RabbitSender import RabbitSender

If you don't want to modify sys.path, the only way is to add -m flag when you run it

python -m messaging_system.tests.PublisherSubscriberTest

see How to fix "Attempted relative import in non-package" even with __init__.py

edit

OK, finally I found an ultimate answer: Relative imports for the billionth time

I suggest you read that post carefully, from which I learned a lot.

In short, if you want to do this, you have to add path-to-Rabbit to sys.path.

Community
  • 1
  • 1
laike9m
  • 18,344
  • 20
  • 107
  • 140
  • Oh, yeah. I know about that. That's what I used to do. I consider this as inconvinient and whant to be able import packages in my project without appending them is sys.path. – user1685095 Jan 15 '14 at 11:48
  • It's not working with -m option. Still the same import error. – user1685095 Jan 15 '14 at 14:57
  • @user1685095 what do you think? – laike9m Jan 20 '14 at 13:53
  • Well, basically I don't need relative imports at all. I actually ended up with something like this python -m unittest tests.ArchiveTest – user1685095 Jan 20 '14 at 13:58
  • @user1685095 I'm glad you get it resolved. Maybe it's better to write down what you want to achieve next time. For your original question, that should be enough information. – laike9m Jan 20 '14 at 14:13
  • Yes, I'm sorry. What I've actually wanted was just a part of my question. – user1685095 Jan 21 '14 at 12:07