-1

I am trying to access a function in package1 from inside package 2

project
 |- __init__.py
 |- package1
   |-__init__.py
   |-module1.py
 |- package2
   |-__init__.py
   |-module2.py

package1/__init __.py

from .module1 import my_function

# I have also tried the following:
# from module1 import my_function
# from module1 import *
# import module1
# and also leaving this file empty

package2/module2.py

from ..package1 import my_function

# I have also already tried the following:
# from ..package1 import module1
# from .. package1 import module1
# from ..package1 import my_function
# from .. package1 import my_function
# import sys
# sys.path.append('.')

# import package1
William
  • 61
  • 1
  • 6
  • As it turns out upon further research relative imports across packages are not allowed in Python https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – William Mar 28 '21 at 19:04

1 Answers1

0

Try the following:

  • leave package1/__init __.py empty
  • in package2/module2.py, add: from project.package1.module1 import my_function
  • in your terminal, set the parent directory of project as the current working directory and run: python -m project.package2.module2 >> No error message, my_function outputs as expected
Laurent
  • 12,287
  • 7
  • 21
  • 37