0

Why, in this code, can't I access db or file from inside do_more()?

   def do_stuff(queue):
    db = getDbConn()
    while True:
        file = queue.get()  #DirEntry object
        ...
        do_more(otherObject)
        q.task_done()    

I'm aware I could pass db and file as arguments to do_more(), but I feel like those variables should just be available in functions called from other functions. It works that way from main to first level functions. What am I missing here?

Stephan B
  • 58
  • 8
  • Short answer: Python, like most modern programming languages, uses lexical (aka static) scope (outer scope locked in where function is defined), not dynamic scope (outer scope depends on call site, changes every time). The only way your code works is with dynamic scope, which is not a thing in Python (not without insane hacks as exhibited in the duplicate). If you want `do_more` to have access to the local variables in `do_stuff`, you need to define it within `do_stuff` so its lexical scope (closure scope in this case) includes the runtime names for than invocation of `do_stuff`. – ShadowRanger Jan 13 '21 at 01:48

2 Answers2

1

In the code you provided, you don't even attempt using the variables from do_stuff.

But as a general rule, you should be able to use variables from a parent function inside a child function, either by passing them as variables or by using them when initializing the child function, like this:

def foo():
    foo2 = "foo"
    def bar():
        print(foo2)
    bar()

foo()

If i did not answer your question let me know.

a_coder
  • 90
  • 1
  • 8
0

no , you cant access those variables , I know what you think , which is wrong. you can access variables inside loops and if statements, not here.

imagine you have a function which is used in many different places, in that case you have access from this function to many variables which makes things complicated.

functions should be stand-alone objects which take some arguments do stuff and return something.so inside a function scope you can only see variables which are defined there and the arguments passed from the parent function using parenthesis.

Toby Maguire
  • 146
  • 1
  • 11