简体   繁体   中英

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:

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?

Due to how local variables are implemented in python you cannot do this. 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). 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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