Qibin Zhou
Qibin Zhou

Reputation: 3

Absolute import in conda env

I met with a problem with absolute import when using conda env. Here is the structure of my project.

In package_1.subpackage_1.run.py there is an absolute import import package_1.file_1. However, when I ran python package_1/subpackage_1/run.py in package folder, I got an error: ModuleNotFoundError: No module named 'package_1'. I tried to print sys.path. project.package_1.subpackage_1 is in sys.path, but the folder from where I ran the command, project is not. I tried to add project in PATH or PYTHONPATH, but it doesn't work in conda env. Does anyone know how to fix this? Thanks!!!

Upvotes: 0

Views: 803

Answers (2)

Rahul P
Rahul P

Reputation: 2663

One of the ways to do this is to add the directory to your sys.path with this code at the top of run.py

import sys
import os

sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'package_1'))

And then change the line in run.py

import package_1.file_1

to

import file_1

Now python can import file1 directly since its directory is on the path.

Upvotes: 1

Aposhian
Aposhian

Reputation: 869

Summary

You can accomplish what you want with relative imports, or with absolute imports if you restructure your project. Modifying your sys.path or PYTHONPATH should not be your go-to solution. If you really want global availability, you could install your local package with conda.

Option 1: Relative Imports

If you want to be able to run a file inside a sub-module directly (i.e. python package_1/subpackage_1/run.py) then you should consider using relative imports.

Example:

project/
  package_1/
    __init__.py
    file_1.py
    subpackage_1/
      __init__.py
      run.py
# run.py

import ..file_1

Option 2: Absolute Imports

If you want to use absolute imports, then your entry point (the script that you run) should be in the top level (package_1) instead of inside a sub-package.

Example:

project/
  package_1/
    __init__.py
    run.py
    file_1.py
    subpackage_1/
      __init__.py
      stuff.py
# run.py

import package_1.subpackage_1.stuff

stuff.run()

# stuff.py

import package_1.file_1

Option 3: Installing your local package with conda

Once you configure your package correctly you should be able to simply run

conda install .

Which will install your local package as if it were a published package. This is likely overkill for your needs.

Why not modify PYTHONPATH or sys.path?

If you rely on having your local package path on PYTHONPATH, you every time you move the project or copy it onto a new computer.

Appending entries to sys.path in code often accomplishes a similar effect to what you can do with relative imports, but later import statements lose semantics.

Upvotes: 0

Related Questions