How to make global imports from a function?

2020-01-28 05:14发布

I fear that this is a messy way to approach the problem but...

let's say that I want to make some imports in Python based on some conditions.

For this reason I want to write a function:

def conditional_import_modules(test):
    if test == 'foo':
        import onemodule, anothermodule
    elif test == 'bar':
        import thirdmodule, and_another_module
    else:
        import all_the_other_modules

Now how can I have the imported modules globally available?

For example:

conditional_import_modules(test='bar')
thirdmodule.myfunction()

7条回答
Luminary・发光体
2楼-- · 2020-01-28 05:18

Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.

Example:

>>> math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> def f():
...     global math
...     import math
...
>>> f()
>>> math
<module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>
查看更多
闹够了就滚
3楼-- · 2020-01-28 05:30

You can use the built-in function __import__ to conditionally import a module with global scope.

To import a top level module (think: import foo):

def cond_import():
  global foo
  foo = __import__('foo', globals(), locals()) 

Import from a hierarchy (think: import foo.bar):

def cond_import():
  global foo
  foo = __import__('foo.bar', globals(), locals()) 

Import from a hierarchy and alias (think: import foo.bar as bar):

def cond_import():
  global bar
  foo = __import__('foo.bar', globals(), locals()) 
  bar = foo.bar
查看更多
别忘想泡老子
4楼-- · 2020-01-28 05:32

I like @rafał grabie approach. As it even support importing all. i.e. from os import *

(Despite it being bad practice XD )

Not allowed to comment, but here is a python 2.7 version.

Also removed the need to call the function at the end.

class GlobalImport:
    def __enter__(self):
        return self
    def __exit__(self, *args):
        import inspect
        collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1][0]).locals
        globals().update(collector)

def test():
    with GlobalImport() as gi:
        ## will fire a warning as its bad practice for python. 
        from os import *

test()
print path.exists(__file__)
查看更多
一纸荒年 Trace。
5楼-- · 2020-01-28 05:37

You can make the imports global within a function like this:

def my_imports(module_name):
    globals()[module_name] = __import__(module_name)
查看更多
Emotional °昔
6楼-- · 2020-01-28 05:38

You could have this function return the names of the modules you want to import, and then use

mod == __import__(module_name)
查看更多
男人必须洒脱
7楼-- · 2020-01-28 05:42

I like @badzil approach.

def global_imports(modulename,shortname = None, asfunction = False):
    if shortname is None: 
        shortname = modulename
    if asfunction is False:
        globals()[shortname] = __import__(modulename)
    else:        
        globals()[shortname] = eval(modulename + "." + shortname)

So something that is traditionally in a class module:

import numpy as np

import rpy2
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects.packages import importr

Can be transformed into a global scope:

global_imports("numpy","np")

global_imports("rpy2")
global_imports("rpy2.robjects","robjects")
global_imports("rpy2.robjects.packages","rpackages")
global_imports("rpy2.robjects.packages","importr",True)

May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"

查看更多
登录 后发表回答