2

I have the following simple project and package structure:

Project/
    package/
        __init__.py
        a.py
            class One: ...
            class Two: ...
        b.py
            from . import a
            class Three: ...
            class Four: ...

I want users to be able to use it as such:

import package
# or
from package import Three, Four
from package.a import One, Two
# or
from package import a

I've tried several uses of from...import in the __init__.py but to no avail! Here's a summary of what I've tried to put in Project/package/__init__.py and the errors they produced when attempting to import package:

from .b import Three, Four
#  ImportError: No module named 'package.b'  
---
from b import Three, Four
#  ImportError: No module named 'b'
---
from package.b import Three, Four
# ImportError: cannot import name Three

I thought I had already solved this problem in my last project... (see: this answer)

TL;DR What do I need to put in Project/package/__init__.py such that users can then import classes Three and Four directly from my package without needing to know in which module they exist? In other words, how can I flatten the namespace of module b?

Edit: using Python 3.3, but I may switch to 3.4 and I may also need to support 2.7.

Edit: added a TL;DR

Edit: significantly reformatted the question for clarity

Edit: updated title to reflect the clarity :)

Edit: added reference to a similar (solved) question that doesn't seem to work in this case

Community
  • 1
  • 1
rhgrant10
  • 179
  • 8

1 Answers1

0

You don't use the dot: it's as simple as that.

In b.py:

from a import Three, Four

It seems that your program is looking for a package.b, not just b. This probably means that using a . won't work

Output from from .a import

File "/storage/emulated/0/com.hipipal.qpyplus/scripts3/.last_tmp.py",   line 1, in <module>
from .a import One, Two
ValueError: Attempted relative import in non-package

Output from from a import (expected)

1
2
Beta Decay
  • 805
  • 1
  • 8
  • 20