0

I just want to import python file with hyper parameters in the parent directory, but I just got the system error.

Parent module '' not loaded, cannot perform relative import

The directory structure is as below.

Project directory
+-- package
|   +-- dataset
|   |   +-- __init__.py
|   |   +-- dataset.py
|   +-- models
|       +-- __init__.py
|       +-- cnn.py
+-- __init__.py
+-- hparams.py
+-- main.py

What I want to do is import variables of hparams.py in dataset.py

I've tried several lines as below, but none of these works.

from ..hparams import * 

from ...hparams import *

from .. import hparams

from ... import hparams

What should I do for import?

Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
S. Yong
  • 79
  • 1
  • 5

1 Answers1

0

You need to tell python where to look for this file, you can't do it by default like you're trying to do. Besides, as your directory architecture suggests, you need to look in the parent directory of the parent directory of your file dataset.py in order to access hparams.py. So what you can do is just add these 2 lines of code at the beginning of dataset.py

import sys
sys.path.insert(0, '..\..')

Then you can perform from hparams import * or import hparams as usual. More info about sys.path.insert Here

offhmax
  • 34
  • 3