0

Problem

Hi. I'm having issues importing a module I wrote. The module I want to import is called neural_networks, defined in the neural_networks.py file.

Directory tree:

├── neural_networks.py └── directory ├── neural_networks.py └── calling_module.py 

neural_networks.py

def function_to_import(): pass 

I read Python 3 docs in the section 5.7. Package Relative Imports, and applyed what's written there, but it's not all working.

calling_module.py

// ImportError: attempted relative import with no known parent package from . import neural_networks // SyntaxError: invalid syntax import ..neural_networks // ImportError: attempted relative import with no known parent package from ..directory import neural_networks // SyntaxError: invalid syntax import .neural_networks // works and i can use function_to_import() using neural_networks.function_to_import() import neural_networks 

Question

How can I correctly import and use neural_networks module in calling_module?

Thanks in advance.

0

2 Answers 2

2

@tlentali has answered the correct way but If you want to use absolute path instead of the relative path, you can do it like this

import os,inspect,sys current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.append(parent_dir) 

and then just import it,

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

1 Comment

Thanks @LakshikaParihar, I appreciate and I take note !
1

We can add the parent path using sys before calling other imports :

import sys sys.path.append("..") 

Then :

from neural_networks import neural_networks 

In addition, you can add an __init__.py file (empty) in the directory containing the .py to import.

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.