Import everything in a Python module inside a function -


i construct function emulates from package_name import *. while this question answers how 1 might modifying globals(). globals(), however, local module function defined in.

for example, suppose define following function in first_package.py,

import imp  def load_contents(path):   """load package"""   module = imp.load_source('', path)   k in dir(module):     if not '__' in k:   # ignore __xxx__ private variables       globals()[k] = getattr(module, k) 

then run following code in second_package.py

import first_package  first_package.load_contents('third_package.py') 

nothing happen. how can fix this?

the trick use sys._getframe go call stack 1 step, retrieve globals of caller. precise code is,

def load_contents(path):   """load contents of configuration file"""   module = imp.load_source('', path)   glob = sys._getframe(1).f_globals  # globals of calling module   k in dir(module):     if not '__' in k:   # ignore __xxx__ private variables       glob[k] = getattr(module, k) 

note code work cpython, sys._getframe implementation-specific function.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -