Reputation: 15985
I am having trouble using my classes that I've defined in a module. I've looked at this stackoverlfow post, and the answer seems to be "you don't need imports." This is definitely not the behavior I'm experiencing. I'm using Python 3.3. Here is my directory structure:
root/
__init__.py
mlp/
__init__.py
mlp.py
layers/
__init__.py
hidden_layer.py
dropout_layer.py
My problem is this: the class defined in dropout_layer.py
extends the class in hidden_layer.py
, but when I try to import hidden_layer, I sometimes get an error depending on the directory I execute my code from. For instance, from layers.hidden_layer import HiddenLayer
then I run my code if I execute it from root/mlp
. This import does not work, however, if I execute my code from root
. This is strange behavior to me. How can I get this working correctly?
My only non-empty __init__.py
file is in root/mlp/layers/
:
# root/mlp/layers/__init__.py
__all__ = ['hidden_layer', 'dropout_layer']
Upvotes: 1
Views: 76
Reputation: 643
In Python 3 you can prepend a .
for an import relative to the location of the current module:
from .hidden_layer import HiddenLayer
Upvotes: 3