elbajo elbajo - 2 months ago 6
Python Question

Set/access local variable from a function in a function?

I'm trying to set a local variable in

main()
from
insideFCT()
which is starts in
main()
:

def insideFCT():
print "inside"
info = datetime.datetime.now()
print info

def main():
print "starting main"
insideFCT()
functionThatPrint(info) #for the example functionThatPrint() acts like print()

main()


I need to find a way so that it gives me:

starting main
inside
2013-09-19...
2013-09-19...



  • I can't modify
    main()
    at all (it means I can't add "info = insideFCT()" and add a return to
    insideFCT()
    )

  • I can't use global variables because the function is going to be use several times at the same time (threads)

  • Of course this is not at all about getting the time,
    datetime.datetime.now()
    represents an input I can't control



My idea is to find something specific to each
main()
when they start, store "info" in a global dictionnary as
globDict[TheThingSpecific]=info
and then I can acces it using
globDict[TheThingSpecific]
in
functionThatPrint()
(Indeed,
functionThatPrint()
is called in the same function as
insideFCT()
so they have the same "specific thing")

I just found the "something specific" I was looking for. It's
threading.current_thread()


SOLUTION:


  • insideFCT()
    stores info into
    globalDict[str(threading.current_thread())]

  • then I can access it in
    functionThatPrint()
    using the same line because it's the same thread :
    globalDict[str(threading.current_thread())]


Answer

There is no way to set a local variable inside a function scope in python from outside. The scope to which the name info belongs is decided at "compile time" - that is, when the interpreter executes the def main() command.

Since the is no binding to info inside main(), it is assumed to be global or built-in. That's it.