简体   繁体   中英

How to load module with same name as other module in Python?

Let me explain problem - we have such project:

model/__init__.py
model/abstract.py
task/__init__.py
task/model.py

How to load into task/model.py model.abstract what is the syntax for it?

# task/model.py 
import model # it loads task/model.py not model
from model.abstract import test # there is no test exception
# model/abstract.py
test = 1

How to do such import?


Requested more details.

Google App Engine application: - main is main.py

Directory structure:

└───src
    │   app.yaml
    │   index.yaml
    │   main.html
    │   main.py
    │   task_master_api.py
    │
    ├───circle
    │       model.py
    │       __init__.py
    │
    ├───model
    │       abstract.py
    │       xxx.py
    │       __init__.py
    │
    ├───task
    │       model.py
    │       __init__.py
    │
    ├───user
    │       model.py
    │       __init__.py

Exception (see task.model not model in root):

from .. import model     
logging.critical((type(model), model.__name__))

from model.abstract import AbstractNamed, AbstractForgetable

-

CRITICAL 2014-02-17 21:23:36,828 model.py:8] (<type 'module'>, 'task.model')

    from model.abstract import AbstractNamed, AbstractForgetable

ImportError: No module named abstract

Much more related to answer.

from .. import model

Gives exception.

ValueError: Attempted relative import beyond toplevel package  

While the relative imports in ndpu's answer should work, the answer to this question that is burning in my mind is simply this: change the name of your files to avoid this error .

If you have model.py inside the circle directory, how about changing the name to circle_model.py ?

Then, you should be able to import modules without any of the relative import .. business.

Edit - knowing now that you don't want to rename

Make sure you have an __init__.py file in your src directory, then try the relative import from .model.abstract import test

Relative import given in the other answer should just work fine. But it is not working because you have a name conflict. You have both a package and module named model. try to use another name either for your package or module.

I found two tricks to force load modele name into module name :

First forcing only absolute loading:

from __future__ import absolute_import
import name

Second is like previous but more code and more local impact:

save_path = sys.path[:]
sys.path.remove('')
import name
sys.path = save_path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM