module importing itself

D W picture D W · Dec 19, 2013 · Viewed 10.1k times · Source

I'm trying to import a module from an application-specific terminal (Maya in this case, but eventually others). I've downloaded a project off git, and I have a structure like so:

modulename
    submodule
        __init.py__
        subsubmodule
        ...
    submodule
    ...
    __init.py__
    modulename.py

Then in my execution shell, I'm trying to import the module to use on the shell, so I have:

import sys,os
modulepath = 'C:/path/to/module'
sys.path.append(modulepath)
import modulename

If the modulename.py being imported is blank, everything is fine. The first two lines of the module are, however, the module trying to import itself (I don't really know why, seeing as this is someone elses project, but it seems to be important to the structure)

import sys,os
import modulename from modulename as mod

This gets the error:

# Error: ImportError: cannot import name modulename# 

And nothing else can proceed.

Ultimately I'm wondering why a module can't import itself, and/or how to get around that problem?

I have read that a module thinks of itself as being named main so that relative imports don't work, in which case I would expect

import __main__ as mod

to work in its stead, which also does not, with error:

# Error: ImportError: Cannot re-init internal module __main__ #

Which makes total sense.

[The question is, how can I import a module from within itself?]

Answer

Iguananaut picture Iguananaut · Dec 19, 2013

What you have here is a package called "modulename" which contains a sub-module also called "modulename". In other words, "modulename.modulename". This is perfectly valid in Python. The modulename.py module is in turn trying to import something from somewhere else in the package also called "modulename". That's why it looks like it's trying to import "from itself". Admittedly confusing which is why I usually try not to use naming like this myself ;)

The import isn't working because you're adding the top-level package called "modulename" to sys.path when you should be adding the parent directory. The package structure is important.

You can tell a directory in a Python project is a package because it contains an __init__.pyfile.


Update: When I first wrote this it was aimed at Python 2.x. In Python 3 a directory containing Python modules is automatically treated as a package, regardless whether or not there's an __init__.py.


By the way, I don't know what software you're trying to use, but in the off chance it includes a setup.py you should use that to install it.

(As an aside, I don't believe the original file actually contains import modulename from modulename as mod as that's invalid syntax.)