4

I have a following file structure:

mymodule/
    __init__.py
    mylib.py
test.py

File mymodule/__init__.py:

# mymodule/__init__.py
def call_me():
    module = __import__('.mylib')
    module.my_func()

File mymodule/mylib.py:

# mymodule/mylib.py
def my_func():
    print("hi!")

File test.py:

# test.py
from mymodule import call_me
call_me()

If I run python3 test.py it fails with the error:

    module = __import__('.mylib')
ImportError: No module named '.mylib'

I want to perform a relative import inside of call_me that equals to the static import from . import mylib. How can I do it?

2
  • Would yhis be a solution? def call_me(): from mymodule import mylib mylib.my_func() Commented Nov 28, 2017 at 10:58
  • Not really, I would like to NOT use the original name of the package inside. In other words, I need a relative import. Commented Nov 28, 2017 at 11:06

2 Answers 2

11

Use importlib.import_module and specify your package from __name__ in __init__.py:

importlib.import_module(name, package=None) Import a module.

The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import.

Example:

import importlib

def call_me():
    module = importlib.import_module('.mylib', package=__name__)
    module.my_func()
Sign up to request clarification or add additional context in comments.

4 Comments

It didn't help: importlib.import_module('mylib', package=None) leads ImportError: No module named 'mylib'
@Fomalhaut because there is no such module... you need the name of the outer module, in this case that would be mymodule - so it know to import mymodule.mylib instead of mylib.mylib
Then that's not a solution, because if I have to use the name mymodule inside, that's not a relative import.
@Fomalhaut well, then why do you need the relative import? presumably to encapsulate your module so one can do from yourmodule import something for this you need to know how you would like to refer to your module, otherwise it can't be done - at least not without horrible hacks
3

How about this,

def call_me():
    mylib = __import__('mylib', globals(), locals(), [], 1)
    mylib.my_func()

Please refer the doc: import

Comments

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.