Python - fails importing package

14,332

Solution 1

To perform these imports you have 3 options, I'll list them in the order I'd prefer. (For all of these options I will be assuming python 3)

Relative imports

Your file structure looks like a proper package file structure so this should work however anyone else trying this option should note that it requires you to be in a package; this won't work for some random script.

You'll also need to run the script doing the importing from outside the package, for example by importing it and running it from there rather than just running the cmp2locus.py script directly

Then you'll need to change your imports to be relative by using .. So:

import filelib.modelmaker.command_file

becomes

from ..modelmaker import command_file

The .. refers to the parent folder (like the hidden file in file systems). Also note you have to use the from import syntax because names starting with .. aren't valid identifiers in python. However you can of course import it as whatever you'd like using from import as.

See also the PEP

Absolute imports

If you place your package in site-packages (the directories returned by site.getsitepackages()) you will be able to use the format of imports that you were trying to use in the question. Note that this requires any users of your package to install it there too so this isn't ideal (although they probably would, relying on it is bad).

Modifying the python path

As Meera answered you can also directly modify the python path by using sys.

I dislike this option personally as it feels very 'hacky' but I've been told it can be useful as it gives you precise control of what you can import.

Solution 2

To import from another folder, you have to append that path of the folder to sys.path:

import sys
sys.path.append('path/filelib/modelmaker')
import command_file
Share:
14,332
duanerf
Author by

duanerf

Updated on June 06, 2022

Comments

  • duanerf
    duanerf about 2 years

    I have trouble importing package. My file structure is like this:

    filelib/  
        __init__.py
        converters/ 
            __init__.py
            cmp2locus.py
        modelmaker/ 
            __init__.py
            command_file.py
    

    In module command_file.py I have a class named CommandFile which i want to call in the cmp2locus.py module.

    I have tried the following in cmp2locus.py module:

    import filelib.modelmaker.command_file
    import modelmaker.command_file
    from filelib.modelmaker.command_file import CommandFile
    

    All these options return ImportError: No modules named ... Appreciate any hint on solving this. I do not understand why this import does not work.