导入与当前模块同名的python标准库 [英] Importing a python standard library with the same name as the current module

查看:70
本文介绍了导入与当前模块同名的python标准库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个 Python 项目,当前模块的名称(我们称之为电子邮件)与标准库中的模块名称相同.我需要从标准库导入,但尝试从库导入时出错.

I'm trying to build a Python project, and the name of the current module (lets call it email) is the same name as a module in the standard library. I need to import from the standard library, but I am getting an error with trying to import from the library.

示例:

Project/
    email.py

# email.py script
import email

# do something with the standard email library.

有什么办法可以保留我的模块 email.py 的名称,还是更改它的最佳选择?我做了一些研究,它们似乎与这样的案例更相关:

Is there any way I can still keep the name of my module email.py, or is the best option changing it? I have done some research, and they seem to relate more to having a case like this:

Project/
    main.py # Current module
    email.py

推荐答案

首先,创建一个隐藏另一个模块的模块是不好的做法.但是,这并不妨碍您继续.

First, it is bad practice to create a module that shadows another module. However, that doesn't prevent you from proceeding.

导入 __future__ import absolute_import 作为您在 main 文件中的第一次导入.

Import __future__ import absolute_import as your first import in your main file.

这会强制导入使用绝对路径而不是相对路径.现在,import email 导入该标准库.您可以通过 from 导入本地版本.导入电子邮件

This forces imports to use absolute paths instead of relative. Now, import email imports that standard library. You can import your local version by from . import email

这篇关于导入与当前模块同名的python标准库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆