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

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

问题描述

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



我做了一些搜索,我似乎找不到解决问题的方法。





任何想法,而无需重命名模块?

解决方案

实际上,解决这个问题相当容易,但实现总是有点脆弱,因为它取决于python导入机制的内部结构,并且在将来的版本中会有所变化。



(以下代码显示如何加载本地和非本地模块以及它们如何共存)

  def import_non_local(name,custom_name = None):
import imp,sys

custom_name = custom_name或name

f,pathname,desc = imp.find_module (name,sys.path [1:])
module = imp.load_module(custom_name,f,pathname,desc)
f.close()

return module

#导入非本地模块,使用自定义名称将其与本地区分开来
#此名称仅在内部用于标识模块。我们通过将其分配给变量日历来决定
#本地范围中的名称。
calendar = import_non_local('calendar','std_calendar')

#正常导入本地模块,作为calendar_local
导入日历作为calendar_local

打印日历.Calendar
print calendar_local

如果可能,最好的解决方案是避免命名模块与标准库或内置模块名称相同的名称。


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?

解决方案

Actually, solving this is rather easy, but the implementation will always be a bit fragile, because it depends python import mechanism's internals and they are subject to change in future versions.

(the following code shows how to load both local and non-local modules and how they may coexist)

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_local
import calendar as calendar_local

print calendar.Calendar
print calendar_local

The best solution, if possible, is to avoid naming your modules with the same name as standard-library or built-in module names.

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

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