简体   繁体   English

导入默认的python包,该包已被另一个同名包覆盖

[英]Import default python package that was overwritten by another package with the same name

I'm working with a library where they thought it would be a good idea to create a module called json which is not at all like the standard json module 我正在与一个图书馆合作,他们认为创建一个名为json的模块是个好主意,而这根本不像标准json模块

Is there a way of importing the default json module? 有没有办法导入默认的json模块?

You can import any module with an alias. 您可以使用别名导入任何模块。 So if they are both named json , you will need to alter the import path. 因此,如果它们都命名为json ,则需要更改导入路径。

>>> import sys
>>> hold, sys.path = sys.path, []
>>> # pop whatever json is already imported
>>> sys.modules.pop('json', None)
>>> # import json from system python
>>> import json as python_json
>>> # clean json from sys.module again
>>> del sys.modules['json']
>>> sys.path = hold
>>> # import the 3rd party json
>>> import json as thrid_json

If you don't remove json from sys.modules , it will still conflict on future imports (which could cause problems) but at least you'll have a handle on both of the packages in the one instance (edited to be more explicit after @Kevin's comment). 如果不从sys.modules删除json ,它将在以后的导入中仍然会发生冲突(这可能会导致问题),但至少您将在一个实例中同时拥有两个包的句柄(编辑后的内容将更加明确) @Kevin的评论)。

A good workaround is to monkeypatch the poorly-named module. 一个好的解决方法是对名称不佳的模块进行猴子补丁

Basically, create a module named notjson , and inside of the __init__ take all the desired objects out of third_json and put them in the __init__ namespace. 基本上,创建一个名为notjson的模块,并在__init__内部将所有所需的对象从third_json ,并将它们放在__init__命名空间中。

If you they have a package structure like this: somepackage.json , then you don't need to do anything special except import with from . 如果您有这样的包结构: somepackage.json ,那么除了使用from导入之外,您不需要做任何特殊的事情。

>>> import json as python_json
>>> from somepackage import json as third_json

In py2 you can use absolute importing 在py2中,您可以使用绝对导入

from __future__ import absolute_import
import json #this imports standard lib json
import mypackage.json as my_json #import custom json module

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM