importing sibling file in a module in python3

Viewed 78

my python project has this directory structure

├── main.py
└── util
    ├── color.py
    ├── __init__.py
    └── student.py

main.py is :

from util.student import fun
fun("calling fun from main")

color.py is :

def color_fun(a):
    print(a)

student.py is :

from color import color_fun

def fun(var):
    color_fun(var)

if __name__ == "__main__":
    fun("calling fun from student")

__init__.py is empty

when I try to run python3 student.py it works as expected. but when I try to run python3 main.py it doesn't work as expected, while it works fine in python2.

I want to run python3 student.py as well as python3 main.py how could I achieve this?

1 Answers

All you need to do is this slight modification in your student.py

def fun(var):
    color_fun(var)

if __name__ == "__main__":
    from color import color_fun
    fun("calling fun from student")
else:
    from util.color import color_fun

The PYTHONPATH for Python3 is causing the problem

Related