简体   繁体   English

初始化/导入子模块而不会污染全局名称空间

[英]Initialize/import submodules without polluting the global namespace

Typically when I import modules, I prefer to just import the top module and treat everything as a member of that, rather than importing each function I need into the global namespace, ie: 通常,当我导入模块时,我更喜欢仅导入顶部模块并将所有模块都视为该模块的成员,而不是将我需要的每个函数导入全局名称空间,即:

import os
os.walk()

instead of: 代替:

from os import walk
walk()

However, I recently came across modules that have submodules that seemingly have to be imported globally in order to run. 但是,我最近遇到了一些模块,这些模块的子模块似乎必须全局导入才能运行。 For example, the Scikit-Learn module contains the "cluster" submodule. 例如,Scikit-Learn模块包含“集群”子模块。 I want to do this: 我想做这个:

import sklearn as skl
skl.cluster.KMeans(...)

but this throws an error because I didn't initialize sklearn.cluster . 但这引发了错误,因为我没有初始化sklearn.cluster Instead I have seen this: 相反,我看到了这一点:

from sklearn import cluster
cluster.KMeans(...)

I really don't like this because I don't like polluting my global namespace. 我真的不喜欢这样,因为我不喜欢污染我的全局名称空间。 Is there any way around this? 有没有办法解决? I tried this: 我尝试了这个:

import sklearn as skl
import skl.cluster

but that doesn't work either. 但这也不起作用。 How can I initialize a submodule without importing it globally? 如何初始化子模块而不将其全局导入?

import sklearn as skl
import sklearn.cluster

The name after the import has to be the actual name of the module, not an alias. import后的名称必须是模块的实际名称,而不是别名。 This does mean that you will end up with the sklearn name as well as the skl name bound to the sklearn module object. 这确实意味着您最终将获得sklearn名称以及绑定到sklearn模块对象的skl名称。

There is no import that will initialize sklearn.cluster and bind the skl name to the sklearn module. 没有导入将初始化sklearn.cluster 并将 skl名称绑定到sklearn模块。 The closest you can do is del sklearn after importing the submodules, or shove the submodule initialization imports somewhere where they won't bind names in this namespace, like a dedicated function or module or something (but hiding imports like that has its own issues), or use importlib.import_module to load the submodules. 导入子模块后,您可以执行的最接近的操作是del sklearn ,或者将子模块初始化导入推到某个地方,在这些地方,它们不会绑定此命名空间中的名称,例如专用函数或模块之类的东西(但是隐藏这样的导入具有其自身的问题) ,或使用importlib.import_module加载子模块。

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

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