Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make these relative imports work in Python 3?
    text
    copied!<p>I have a directory structure that looks like this:</p> <pre><code>project/ __init__.py foo/ __init.py__ first.py second.py third.py plum.py </code></pre> <p>In <code>project/foo/__init__.py</code> I import classes from <code>first.py</code>, <code>second.py</code> and <code>third.py</code> and put them in <code>__all__</code>.</p> <p>There's a class in <code>first.py</code> named <code>WonderfulThing</code> which I'd like to use in <code>second.py</code>, and want to import by importing <code>*</code> from <code>foo</code>. (It's outside of the scope of this question why I'd like to do so, assume I have a good reason.)</p> <p>In <code>second.py</code> I've tried <code>from .foo import *</code>, <code>from foo import *</code> and <code>from . import *</code> and in none of these cases is <code>WonderfulThing</code> imported. I also tried <code>from ..foo import *</code>, which raises an error "Attempted relative import beyond toplevel package".</p> <p>I've read the docs and the PEP, and I can't work out how to make this work. Any assistance would be appreciated.</p> <p><strong>Clarification/Edit:</strong> It seems like I may have been misunderstanding the way <code>__all__</code> works in packages. I was using it the same as in modules,</p> <pre><code>from .first import WonderfulThing __all__ = [ "WonderfulThing" ] </code></pre> <p>but looking at the docs again it seems to suggest that <code>__all__</code> may only be used in packages to specify the names of modules to be imported by default; there doesn't seem to be any way to include anything that's not a module.</p> <p>Is this correct?</p> <p><strong>Edit:</strong> A non-wildcard import failed (<code>cannot import name WonderfulThing</code>). Trying <code>from . import foo</code> failed, but <code>import foo</code> works. Unfortunately, <code>dir(foo)</code> shows nothing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload