I post this answer but I'm not quite really sure if I understood your question. You referred to this question: Global Variable from a different file Python
However I believe that I am not getting an output from the variable file.foo
because foo
is not explicitly defined in file.py
. foo
is an array of matrices created from a readfile.
You referred to file.foo
as not explicitly defined in file
. What I understand from your statement is that, foo
lives within another object that lives in file
module. So in order to get foo
you need to fetch it through that object:
import file
file.object.foo
or:
import file *
object.foo
file.py
appends values from the readfile to foo
thus file.py
must run independently to define foo
.
You would basically import file
module in order to append the values from the readfile. Hence, within file
you would open the readfile to append its values to foo
which is basically an object of file
: file.foo
.
I just hope that I got your what you're asking about.
Edit:
Let's suppose the code you posted is in a module file called file
:
color_matrices = Full_Layout(array=org_arr, resolution=1)
def Globalize_RPF():
global color_matrices
color_matrices
is global because it's assigned at the top-level of the module. This statement global color_matrices
inside Globalize_RPF
function will declare that you intend to change the global variable color_matrices
:
def Globalize_RPF():
color_matrices = Full_Layout(array=org_arr, resolution=1) # Local to function, you cannot use `file.foo` after importing `file` module
When assigned this way, color_matrices
is local to the function. What does that mean? It means the variable won't be accessible outside the function. So even if you try to use color_matrices
after the function in file
module, it won't work.
color_matrices = Full_Layout(array=org_arr, resolution=1) # Top-level assignment, global var
def Globalize_RPF():
# process color_matrices
Now color_matrices
is a global variable, that's you can use it inside file
module in functions, classes, in expressions and many other places, you can reference the variable anywhere in file
because its global now. Because color_matrices
is global now and not a local variable inside a function, we can get its value by importing file
like the following:
from file import color_matrices
RPF = color_matrices
print(RPF)
If you need to re-assign color_matrices
to new results inside the function, use global
keyword:
def Globalize_RPF():
global color_matrices
color_matrices = ... # Changes global color_matrices
If you use only color_matrices = ...
inside the function body you'll simply create color_matrices
that's local to the function and you'll shadow/override color_matrices
of the global scope, the one that's assigned at the top of the module.