pythonglobal

python won't update globals from imported function


I wrote a script to parse arguments from the command line. It has a function called getFlags which parses sys.argv and a command string from the user to create a dictionary called myVars with the variable name and associated values, and returns the dictionary. If I include the function in the main script I can move those variables to the globals() list by simply doing globals().update(myVars) inside the function.

However, when I save this function and import it, the update function does not work and I am forced to use globals().update(getFlags(...)). This works fine for me but confuses some people who use my script.

How can I make it update the globals using the imported function?

Example

def getFlags(commandString,usage="No usage was provided"):
   ....
   globals().update(myVars)
   return myVars


getFlags("...")

#My variables are now in the global scope
from myScripts import getFlags

getFlags("...") 
#Oh no, variables not in global scope
globals().update(getFlags("...")
#Now the variables are in the global scope

Solution

  • Despite the name, the global namespace is not just one thing. There are separate global namespaces for each module. When code is run, it uses the global namespace for the module it was written in.

    This is why the globals.update call you make in getFlags doesn't work as you want. It updates the global namespace of the myScripts module, rather than the global namespace of the calling code.

    You could probably use inspect to walk the stack frames and find the global namespace of the caller, but I strongly suspect that it is not worth it. Adding stuff to a module's global namespace, especially with user-supplied data seems like a really bad idea. What if it redefined one of your functions? Or a builtin, like list or print?