Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError when trying to import a custom module in Python

Tags:

python

module

Note that I searched SO for this error and while there were many similar questions, I didn't find one that addressed this particular issue.

I'm working on a Python module that looks like this:

/com
    /company
        /foo
        /bar

I'm editing a source file within the bar directory and attempting to import classes that live in the foo directory. I've tried importing the files the following ways:

from com.company.foo import *
from company.foo import *
from foo import *
import com.company.foo
import company.foo
import foo

Each of these produces a similar error:

ImportError: no module named com.company.foo

I have __init__.py files in each of the directories, including the directory that contains com.

Not sure what I'm doing wrong here - thanks in advance for you assistance!

like image 341
brettkelly Avatar asked May 03 '11 21:05

brettkelly


People also ask

Why can't I import modules in Python?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

How do you fix ImportError Cannot import name in Python?

The Python "ImportError: cannot import name" occurs when we have circular imports (importing members between the same files). To solve the error, move the objects to a third file and import them from a central location in other files, or nest one of the imports in a function.

How do I resolve ImportError no module name?

To get rid of this error “ImportError: No module named”, you just need to create __init__.py in the appropriate directory and everything will work fine.

What is ImportError in Python?

In Python, ImportError occurs when the Python program tries to import module which does not exist in the private table. This exception can be avoided using exception handling using try and except blocks. We also saw examples of how the ImportError occurs and how it is handled.


1 Answers

The directory containing /com needs to be on the Python path. There are a number of ways to do this:

  1. At the command line, every time:

    user@host:~$ PYTHONPATH=/path/to/whatever python some_file.py

  2. In your shell configuration (.bashrc, .bash_profile, etc):

    export PYTHONPATH=/path/to/whatever

  3. In Python code (I don't recommend this, as general practice):

    import sys
    sys.path.append('/path/to/whatever')

As some of the commenters said, usually this is handled either by the container (mod_wsgi, etc) or by your bootstrap/main script (which might do something like option #3, or might be invoked in an environment set up as in options #1 or #2)

like image 157
dcrosta Avatar answered Sep 20 '22 13:09

dcrosta