简体   繁体   English

如何在函数中执行“导入*”?

[英]How can I perform `import *` from within a function?

I have the following standard import procedure: 我有以下标准导入过程:

from ROOT import *

Because of the way ROOT handles command line options and arguments, something like the following is required in order to avoid screwing up the script's command line parsing: 由于ROOT处理命令行选项和参数的方式,因此需要执行以下类似操作,以避免搞乱脚本的命令行解析:

argv_tmp = sys.argv
sys.argv = []
from ROOT import *
sys.argv = argv_tmp

I need to perform this operation in many scripts. 我需要在许多脚本中执行此操作。 This operation may change or there might turn out to be a better approach, so I want to centralise this procedure in a single function provided by some imported module, making it easy to change the procedure in future. 此操作可能会更改,或者可能会发现有更好的方法,所以我想将此过程集中在某个导入模块提供的单个功能中,以便将来轻松更改过程。

def import_ROOT():
    # magic

import os
import sys
import_ROOT()
import docopt

How can I import the ROOT module from within a function such that the result of the script's operation is the same as for the from ROOT import * procedure described above? 如何从函数中导入ROOT模块,以使脚本操作的结果与上述的from ROOT import *过程相同?

Due to how local variables are implemented in python you cannot do this. 由于在python中如何实现局部变量,因此您无法执行此操作。 And since you don't know all the variables that may be imported you can't declare them global. 而且由于您不知道所有可能导入的变量,因此无法将它们声明为全局变量。

As to why you can't import unknown locals in a function. 至于为什么不能在函数中导入未知的本地人。 This is because at compile time python establishes all the different possible locals that may exist (anything that is directly assigned to and hasn't been declared global or nonlocal). 这是因为python在编译时会建立可能存在的所有可能的本地变量(直接分配给全局变量或未声明为全局变量或非本地变量的任何局部变量)。 Space for these locals are made in an array associated with each call of the function. 这些局部变量的空间在与函数的每次调用关联的数组中进行。 All locals are then referenced by their index in the array rather than their name. 然后,通过数组中的索引而不是其名称来引用所有本地人。 Thus, the interpreter is unable to make additional space for unknown locals nor know how to refer to them at runtime. 因此,解释器无法为未知的本地人留出更多空间,也无法在运行时知道如何引用它们。

I believe there's already a similiar question in here: 我相信这里已经有一个类似的问题:

Python: how to make global imports from a function Python:如何从函数进行全局导入

example: 例:

def example_function():
    global module
    import module

This probably misses all sorts of corner cases, but it's a start: 这可能会错过各种极端情况,但这是一个开始:

def import_ROOT():
    import ROOT
    globals().update(ROOT.__dict__)

Obligatory disclaimer: if you're importing *, you're probably doing it wrong. 强制性免责声明:如果要导入*,则可能是错误的。 But I guess there could be situations where import * is the lesser evil. 但我猜可能存在以下情况:import *是次要的邪恶。

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

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