当存在具有相同名称的同级文件时导入Python模块

2024-04-27 03:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下文件

tata/foo.py
tata/yoyo.py

foo/__init__.py
foo/bar.py

在文件foo.py中我知道

import foo.bar

我运行PYTHONPATH=. python tata/yoyo.py得到

Traceback (most recent call last):
  File "tata/yoyo.py", line 1, in <module>
    import foo.bar
ImportError: No module named bar

当我删除tata/foo.py时,问题就消失了。当我的全局模块名和本地文件名一致时,您能建议一种解决我的问题的方法吗。你知道吗


Tags: 文件pyimportmostfooinitbarcall
3条回答

这是一个例子:

文件:

test
|
import_test
├── foo
│   ├── bar.py
│   ├── bar.pyc
│   ├── __init__.py
│   └── __init__.pyc
├── __init__.py
├── __init__.pyc
└── tata
    ├── foo.py
    ├── foo.pyc
    ├── __init__.py
    ├── __init__.pyc
    └── yoyo.py

你知道吗yoyo.py公司地址:

#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from ..foo import bar


print 'cool'

测试命令:

cd test    
python -m import_test.tata.yoyo

输出:

cool

这似乎是PEP 328中描述的经典问题

a local module or package can shadow another hanging directly off sys.path

要解决这个问题:

  1. 代码应该作为模块而不是脚本执行(-m选项)。你知道吗
  2. 使用具有所谓“绝对导入行为”的python3或add

    from __future__ import absolute_import
    

用途:

from __future__ import absolute_import

相关问题 更多 >