Search code examples
pythonimportmodulepiplocal

Python3 module import confusion


When I install a python module (for example mediafile) with pip I can import it like this:

from mediafile import MediaFile

and it works perfectly.

But then I install it to a different location (pip install --target="C:/msys64/home/myname/myprogram/tools/mediafile/" mediafile), I can only import it like this:

from tools import mediafile

and importing MediaFile just doesn't work. (I tried from tools.mediafile import MediaFile and a couple of other variations with no success).

Here's an ouptut :

ImportError: cannot import name 'MediaFile' from 'tools.mediafile' (unknown location)

When I try to use mediafile.MediaFile it gives me this error :

AttributeError: module 'tools.mediafile' has no attribute 'MediaFile'

Any idea where I got the syntax wrong?


Solution

  • The command pip install --target=/path/to/package mypackage will install the package inside the directory you have specified, i.e. at /path/to/package/mypackage. In your case it is probably at C:/msys64/home/myname/myprogram/tools/mediafile/mediafile.

    If this is the case you should be able to import it with:

    from tools.mediafile.mediafile import MediaFile
    

    but don't do this - instead you should delete it and reinstall with

    pip install --target="C:/msys64/home/myname/myprogram/tools/" mediafile
    

    Then you should be able to import it with

    from tools.mediafile import Mediafile
    

    The problem with the above approach, as you have discovered, is that packages will expect to be able to import their own dependencies just using import dependency - they will not know about your tools directory. To fix this, and to make your own imports easier, you will need to add the directory to your PYTHONPATH environment variable. See e.g. this question for how to do this in Windows.

    Alternatively you can add it inside the script itself:

    import sys
    sys.path.append("tools")
    from mediafile import MediaFile
    

    However setting PYTHONPATH is the preferred way to do this.

    Note that I have assumed you deleted and reinstalled mediafile as above, so your directory structure should be:

    tools
    ├── mediafile.py
    ├── mutagen
    ├── ...