Home > other >  Why Python can access variable in function which was defined outside of function
Why Python can access variable in function which was defined outside of function

Time:05-28

Why Python can access variable in function which was defined outside of function. This mysterious_var was defined outside but how Python can access it in function?

 def show_truth():
        print(mysterious_var)
        
 mysterious_var = 'Surprise!'
        
 show_truth()

CodePudding user response:

You need to understand the concept of flow of control in python.. So lets take your code as an example.

So the flow of control would be something like this.

1 -> Line number one(defining your function and storing its reference in the RAM) Remember, the flow of control will not move into the function as of now because the function in line 1 has just been defined, it hasn't been called yet.

2 -> Line number 3(assigning the variable)

3 -> Line number 4(Calling the function)

4 -> Line number 1 again(It will move onto the line number 1 as you called the function)

5 -> The code inside the function.

Now if you realize the variable has already been defined and assigned in the step 3. So the code inside your function recognizes the variable and does not produce any errors.

CodePudding user response:

The short answer? You've defined mysterious_var as a global variable and your function has access to the global namespace.


From the Python Docs about functions...

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.

You can always check your global and local members by printing globals() and locals() respectively.

  • Related