module importing itself

为君一笑 提交于 2021-01-23 06:19:12

问题


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?]


回答1:


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.)



来源:https://stackoverflow.com/questions/20686684/module-importing-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!