简体   繁体   English

python:在包名称空间中导入模块

[英]python: importing module in package namespace

I wonder if there is some standard way to do something like 我想知道是否有某种标准的方式来做类似的事情

import scipy as sp
from scipy import interpolate as sp.interpolate

that is not allowed. 那是不允许的。

Specifically: 特别:

  1. I'd like to know if there is some reason why the above is not allowed. 我想知道是否有某些原因导致上述内容不被允许。 If I'm developing my own package foo, it seems reasonable to pollute its namespace as little as possible. 如果我正在开发自己的软件包foo,则尽可能减少其名称空间是合理的。

  2. Things like

     import scipy as sp __import__('scipy.interpolate') 

    do the job, but are not all that nice and the docs recommend not to use __import__ , unless strictly necessarily. 做这项工作,但不是很好,文档建议不要使用__import__ ,除非严格必要。 Similarly 同样

     import importlib import scipy as sp importlib.import_module('scipy.interpolate',sp) 

does the job, but it is still ugly, even longer and puts importlib in the namespace... 做这项工作,但它仍然很丑,甚至更长,并将importlib放在命名空间中...

Imported modules are treated like regular objects so if you really want to you can import a module and assign it to an arbitrary variable like so 导入的模块被视为常规对象,因此,如果您确实要导入模块,可以将其分配给任意变量,如下所示

import scipy as sp
from scipy import interpolate 
sp.interpolate = interpolate

sp.interpolate will behave as expected, it just points to the interpolate module whenever you call sp.interpolate. sp.interpolate的行为将与预期的一样,只要您调用sp.interpolate,它就指向插值模块。 They are the same object underneath, ie 它们是相同的物体,即

print sp.interpolate is interpolate
>>> True

Then to finally remove the original 'interpolate' pointer call 然后最终删除原始的“插值”指针调用

del interpolate

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

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