How to dynamically modify a function's local namespace?

后端 未结 3 938
走了就别回头了
走了就别回头了 2021-01-13 17:11

NB: This question assumes Python 2.7.3.

I\'m looking for a sane approach to dynamically modify a function\'s local namespace, preferably in a way that adds the lea

3条回答
  •  遥遥无期
    2021-01-13 17:56

    Not sure if it is possible with an external function only. I've created a snippet:

    def get_module_prefix(mod, localsDict):
        for name, value in localsDict.iteritems():
            if value == mod:
                return name
        raise Exception("Not found")
    
    def get_new_locals(mod, localsDict):
        modulePrefix = get_module_prefix(mod, localsDict)
        stmts = []
        for name in dir(mod):
            if name.startswith('_'):
                continue
            if name not in localsDict:
                continue
            stmts.append("%s = %s.%s" % (name, modulePrefix, name))
        return "\n".join(stmts)
    
    def func(someName):
        from some.dotted.prefix import some.dotted.name
        #here we update locals
        exec(get_new_locals(some.dotted.name, "some.dotted.name", locals()))
        print locals()
        print someName # value taken from aModule instead of parameter value
    
    
    func(5)
    

    where:

    • get_module_prefix is used to find the name under which the module is imported,
    • get_new_locals returns assignment statements which can be used to update locals,

    The actual update of locals is performed in line exec(get_new_locals(some.dotted.name, locals())) where we simply execute assignment statements in which we assign values from the module to local variables.

    I am not sure if it is what you actually ment.

提交回复
热议问题