1

I made my python module which A.py uses B.py like below. In such a case, how do I import B.py in A.py? I want to use mylib module from other directory. But my code doesn't work because of path problem.

├── main.py
└── mylib
    ├── A.py
    ├── B.py
    ├── __init__.py
    └── main_in_mylib.py

A.py

import B
def test():
    B.hello()

B.py

def hello():
    print("hello from B")

main_in_mylib.py

import A
A.test()

main.py

import mylib.A as A
A.test()

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import mylib.A as A
  File "/home/jef/python-module/mylib/A.py", line 3, in <module>
    import B
ModuleNotFoundError: No module named 'B'

Updated

ModuleNotFoundError: No module named 'B'

# main.py
from mylib.A import test
test()

ModuleNotFoundError: No module named 'B'

# main.py
import mylib.B as B
import mylib.A as A
A.test()
1
  • The modules system in python is not always intuitive, but I think the link here will help you understand how things work. Commented May 10, 2017 at 7:10

3 Answers 3

4

you need to change A to

import mylib.B as B
def test():
    B.hello()

instead of

import B
def test():
    B.hello()

because imports are always relative to the script you call (in this case main.py)

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

5 Comments

This is not still clear. Could you check my updates? This may is not correct answer.
you need to do this import in A
Thank you. Now my code is working. By the way, is it common way to import other functions in a such situation?
why not from mylib import B? aliasing seems to be redundant here
@AzatIbrakov I just wanted to keep with the style used in the original question
2

For the record it is also possible here to do a relative import in A.py:

from . import B

1 Comment

It looks useful because I don't need to set specific directory name.
-1

The problem is you imported a file and trying to call methods using dot notation.

use from mylib.A import test

now you can directly use test() inside your main.py

in python3 you don't even have to write __init__.py inside a directory to tell that it is a package (it is a good practice though)

1 Comment

Correction.. U can write from A import test

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.