I have a directory structure that looks like this:
scripts/
__init__.py
filepaths.py
Run.py
domains/
__init__.py
topspin.py
tiles.py
hanoi.py
grid.py
I would like to say:
from scripts import *
and get the stuff that is in filepaths.py but also get the things that are in hanoi.py
The outer __init__.py
contains:
__all__ = ['filepaths','Run','domains','hanoi']
I can't figure out how to get the inner files to be included in that list. Putting hanoi by itself gets this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'hanoi'
Putting domains.hanoi gets this error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'domains.hanoi'
The last reasonable guess I could come up with is putting scripts.domains.hanoi which gets this error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'scripts.domains.hanoi'
How do you get the all list to include things that are in subdirectories?
Import them first, in the
__init__
files.In
scripts/__init__.py
, import at leastdomains
, and inscripts/domains/__init__.py
importhanoi
, etc. Or importdomains.hanoi
directly inscripts/__init__.py
.Without importing these, the
scripts/__init__.py
module has no reference to the nestend packages.In
scripts/__init__.py
, before the__all__
add the followingThis will add those modules to the namespace, and you will be able to import them with
Note
As a soapbox, it is preferred to do things like
over
because 6 months from now, you might look at
hanoi
on the 400th line of code and wonder where it came from if you use the*
import style. By explicitly showing what is imported fromscripts
it serves as a reminder where things come from. I'm sure that anyone trying to read your code in the future will thank you.