2

So I have a directory setup like so:

some_dir/ foo/ bar/ test.py src/ __init__.py data/ __init__.py utils.py 

I want to import utils.py from my test.py module.

import sys.path sys.path.append("../../") from src import data data.utils // this throws an error AttributeError: module 'src.data' has no attribute 'utils' 

But when I do:

import sys.path sys.path.append("../../") from src.data import utils 

Everything works, why is this?

1
  • utils has never been imported. Commented Oct 13, 2018 at 5:49

1 Answer 1

1

a) from src.data import utils will import utils.py, so everything is ok.

b) from src import data will just import the data package, never import utils.py, if you want, you need add explicit import in __init__.py under the folder data, something like follows:

1) If need to support both python3 & python2:

__init__.py:

import src.data.utils # absolute import 

Or:

__init__.py:

from . import utils # relative import 

2) If just need to support python2, make it simple:

__init__.py:

import utils 

Then, when package imported, the __init__.py under this package will also be executed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.