0

I have the following dir structure

mainpackage
├── __init__.py
└── subpackage
    ├── __init__.py
    └── module.py

Module.py contains

def test():
    print("test called")

Using python3 I am looking to make the module.py module available for import in the mainpackage namespace. So far my mainpackage __init__.py file looks like this

from .subpackage import module

I would like to be able to call

import mainpackage.module

but this throws

ImportError: No module named 'mainpackage.module'

Just for clarity, I am NOT looking to import the test function into the mainpackage namespace - I want the entire module. Is this possible ? Any help would be much appreciated.

2 Answers 2

1

As far as I know you cannot make a module of a subpackage available in the namespace of the mainpackage like you tried:

import mainpackage.module

looks for a module in the subdirectory of mainpackage and not in any other (deeper) subdirectories.

What you tried in the mainpackage\__init.py__ is correct. Your

from .subpackage import module 

will make the module availabe on mainpackage level. If you type in an IPython console

import mainpackage
mainpackage.module

will give the following output

<module 'mainpackage.subpackage.module' from 'your\path\mainpackage\subpackage\module.py'>

but import mainpackage.module still won't work. If you now want to use module as an instance you have to use

from mainpackage import module

which will allow you to use your function like this

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

Comments

0

Import it this way from mainpackage.subpackage import module and you don't need from .subpackage import module in the init file

4 Comments

I am aware you can do that but it doesnt make it available in the mainpackage namespace. I want to call import mainpackage.module
do you have another file in the mainpackage which uses subpackage?
Not at the moment no
just call import mainpackage.subpackage.module because it doesn't make any difference what is imported in the mainpackage init file python will still throw the error. Basically you want to import the import but that's doesn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.