当存在同名模块时从内置库导入 [英] Importing from builtin library when module with same name exists

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

问题描述

情况:- 我的 project_folder 中有一个名为日历的模块- 我想使用 Python 库中的内置 Calendar 类- 当我使用 from calendar import Calendar 时,它会抱怨,因为它试图从我的模块加载.

Situation: - There is a module in my project_folder called calendar - I would like to use the built-in Calendar class from the Python libraries - When I use from calendar import Calendar it complains because it's trying to load from my module.

我进行了几次搜索,但似乎找不到解决问题的方法.

I've done a few searches and I can't seem to find a solution to my problem.

无需重命名我的模块的任何想法?

Any ideas without having to rename my module?

推荐答案

已接受的解决方案包含现已弃用的方法.

The accepted solution contains a now-deprecated approach.

importlib 文档这里给出了一个很好的例子,说明了直接从 python >= 3.5 的文件路径加载模块的更合适的方法:

The importlib documentation here gives a good example of the more appropriate way to load a module directly from a file path for python >= 3.5:

import importlib.util
import sys

# For illustrative purposes.
import tokenize
file_path = tokenize.__file__  # returns "/path/to/tokenize.py"
module_name = tokenize.__name__  # returns "tokenize"

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)

因此,您可以从路径加载任何 .py 文件并将模块名称设置为您想要的任何名称.因此,只需将 module_name 调整为您希望模块在导入时具有的任何自定义名称.

So, you can load any .py file from a path and set the module name to be whatever you want. So just adjust the module_name to be whatever custom name you'd like the module to have upon importing.

要加载包而不是单个文件,file_path 应该是包根目录的路径 __init__.py

To load a package instead of a single file, file_path should be the path to the package's root __init__.py

这篇关于当存在同名模块时从内置库导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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