0

I'm trying to import and run a module from a parent directory in python interactive mode. My directory looks like this:

modules:
        tests:

So, I'm trying to import the modules in the modules directory while I'm in the test directory.

This is the what I've tried and the error I'm getting:

>>> new_method = __import__("../0-add_integer.py").add_integer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named '.'
>>> 

However this does not work, please help me out. Thanks in advance.

  • 1
    Do note that Python imports work with _package names_, not files or directories. Imports _do not_ navigate the filesystem, and are only resolved by searching the Python path. There's no way to express "in the parent directory" to the Python import system. The closest you can come is relative imports within a package, but that only works if your inside of a package to begin with. – Brian61354270 Apr 03 '23 at 14:54
  • Yeah, I did not think about it this way. – Enwerem Melvin Apr 03 '23 at 15:02

1 Answers1

0

Okay, I was able to find a solution for this:

>>> import sys
>>> sys.path.append("..") # this adds the parent dir to path
>>> new_method = __import__("0-add_integer").add_integer
>>> new_method(10, 4)
14

NOTE: This is for the purpose of importing and using the module in the parent directory in a child directory.

  • Using `sys.path` in this way is generally a bad practice / unnecessary hack. It's almost always preferable to setup your project so that your packages/modules are on the Python path to begin with. That's generally done by either relying on your CWD being the project root or by installing your project as a distribution package. – Brian61354270 Apr 03 '23 at 15:08