当存在具有相同名称的模块时从内置库导入情况: - 我的project_folder中有一个名为calendar的模块 - 我想使用Python库中的内置Calendar类 - 当我使用日历导入日历时,它会抱怨,因为它试图从我的模块加载。任何想法,而无需重命名我的模块?
3 回答

慕容森
TA贡献1853条经验 获得超18个赞
实际上,解决这个问题相当容易,但实现总是有点脆弱,因为它取决于python导入机制的内部结构,并且它们在未来的版本中会发生变化。
(以下代码显示了如何加载本地和非本地模块以及它们如何共存)
def import_non_local(name, custom_name=None): import imp, sys custom_name = custom_name or name f, pathname, desc = imp.find_module(name, sys.path[1:]) module = imp.load_module(custom_name, f, pathname, desc) f.close() return module# Import non-local module, use a custom name to differentiate it from local# This name is only used internally for identifying the module. We decide# the name in the local scope by assigning it to the variable calendar.calendar = import_non_local('calendar','std_calendar')# import local module normally, as calendar_localimport calendar as calendar_localprint calendar.Calendarprint calendar_local
如果可能,最佳解决方案是避免使用与标准库或内置模块名称相同的名称命名模块。
添加回答
举报
0/150
提交
取消