I have a global variable that's declared inside a function in the functions.py file and I want to access this global variable in the main.py file. How do I achieve that?
# functions.py
def someFunction():
global someVariable
#main.py
from functions import *
someVariable=0
importing module with * gives access to all variables and functions in the current file. This should be working. Please tell me where you are facing a problem in this.
someVariable is defined in someFunction().
If you haven't called someFunction(), so the someVariable is undefined.
You can do this:
in main.py
#main.py
from functions import *
someFunction()
someVariable = 0
or in functions.py
# functions.py
someVariable = 0
One thing that you can do is intstead of declaring it inside function declare it as function attribute like shown below
# functions.py
def someFunction():
#your code
# main.py
from functions import *
setattr(someFunction,'key_name',0) # this is how u set the value
someVariable = getattr(someFunction,'key_name') # this is how u access it
But if real code is not Possible please give a much clearer example code so that we can help you debug the exact problem
Related
Sometimes, I see examples like this, but I don't understand how do they work. Imported module uses function without any places in which this function is set to use. Please can someone explain me how to use them.
Example:
from some_package import *
def some_func():
# do_something
pass
imported_func()
And then imported_func somehow defines some_func and uses it. How is this implemented?
When I tried to call some_func from module.py I received an error. Again: idea is to use function from imported file which was defined in importing file. I couldn't find answer in google.
I tried:
from f.module import *
obj = cls()
def some_func():
for _ in range(100):
print("smth")
obj.imported_func()
Code in main.py
class cls:
#staticmethod
def imported_func():
some_func()
Code in module.py
I have main.py and folder f in one directory. In folder f I have module.py
The way to do this is at first import __main__ then call __main__.some_func(), but remember, it's not a good practice because at least you are reserving name, what can become common reason for errors.
I just bumped into an unexpected (at least, for me!) behavior, and I'm trying to understand it.
Let's say I have a main file:
main.py
from my_packages.module_00 import my_function
def main():
my_function()
if __name__ == "__main__":
main()
and, in the folder "my_packages", the module module_00 containing the function definition for "my_function" and a global variable:
module_00.py
global_var = 'global variable'
def my_function():
print(f'Do I know {global_var}???')
When I run main.py, it outputs:
Do I know global variable???
And I'm trying to figure out why it's working.
I would expect the variable global_var to have a scope limited only to the module where it's defined (the answer to this question seems to confirm it).
Basically, I assumed that importing my_function by
from my_packages.module_00 import my_function
was equivalent to copy/pasting the function definition in main.py. However, it seems that...the imported function somehow keeps track of the global variables declared in the module where the function itself has been defined?
Or am I missing something?
However, it seems that...the imported function somehow keeps track of the global variables declared in the module where the function itself has been defined?
That's exactly what it is doing.
>>> from module_00 import my_func
>>> my_func.__globals__['global_var']
'global variable'
>>> module_00.global_var is my_func.__globals__['global_var']
True
>>> module_00.global_var = 3
>>> my_func.__globals__['global_var']
3
__globals__ is a reference to the global namespace of the module where my_func was defined.
Fix a couple of typos and your code works as expected. Each module in Python has its own private symbol table for the module's global variables.
import in main.py must be my_func not my_function matching the function name as defined in module_00.py.
ref in f-string in module_00.py must be {global_var} not {global variable}.
main.py
from my_packages.module_00 import my_func
^^^^^
def main():
my_func() # my_func not my_function
if __name__ == "__main__":
main()
module_00.py
global_var = 'global variable'
def my_func():
print(f'Do I know {global_var}???')
^^^^^^^^^^
Output:
Do I know global variable???
If you want to access a module's global variable then you can import the module and access the variable with the syntax: package.module_name.variable_name; e.g. my_packages.module_00.global_var
This is partially linked with my last question. I imported an object called current_user. I pass it in 2 variables from file 1 called guy.py, the variables are log_name and log_pass. These 2 variables are inputs from 2 entries and they're global. I made a function to import these global variables along with every other global that I have in gui.py. I'm still confused as to why the global variables are still being undefined.
This is the function which I use to import the object current_user:
def objects():
global log_name,log_pass
current_user = User(log_name,log_pass,score=0)
return current_user
And this is the function I tried using to import my global variables:
def global_vars():
global main_window,reg_window,name_entry,pass_entry,log_name_entry,log_pass_entry,log_name,log_pass,c,conn,query,data
The error I get is this:
current_user = User(log_name,log_pass,score=0)
NameError: name 'log_name' is not defined
as I understand you have to .py files: one is called guy.py the other I will call test.py:
so if you want to import values from guy.py to test.py. First define variables in guy.py like so:
log_name = yourvalue
log_pass = yourvalue
then go to test.py (it has to be in the same directory (to make it simple)) and import:
from guy import log_name, log_pass
now you can use these values in test.py and whenever you change the value in guy.py it will be changed in test.py. Also there is no need to make values global (for this case I think)
I'm bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.
What I did was define them in my projects main.py file, as following:
# ../myproject/main.py
# Define global myList
global myList
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
I'm trying to use myList in subfile.py, as following
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
globals()["myList"].append("hey")
An other way I tried, but didn't work either
# ../myproject/main.py
# Import globfile
import globfile
# Save myList into globfile
globfile.myList = []
# Import subfile
import subfile
# Do something
subfile.stuff()
print(globfile.myList[0])
And inside subfile.py I had this:
# ../myproject/subfile.py
# Import globfile
import globfile
# Save "hey" into myList
def stuff():
globfile.myList.append("hey")
But again, it didn't work. How should I implement this? I understand that it cannot work like that, when the two files don't really know each other (well subfile doesn't know main), but I can't think of how to do it, without using io writing or pickle, which I don't want to do.
The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
Next, your subfile can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
Note that subfile does not call init()— that task belongs to main.py:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.
See Python's document on sharing global variables across modules:
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
config.py:
x = 0 # Default value of the 'x' configuration setting
Import the config module in all modules of your application; the module then becomes available as a global name.
main.py:
import config
print (config.x)
In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.
You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.
A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.
So, in your example:
# ../myproject/main.py
# Define global myList
# global myList - there is no "global" declaration at module level. Just inside
# function and methods
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
And:
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
# You have to make the module main available for the
# code here.
# Placing the import inside the function body will
# usually avoid import cycles -
# unless you happen to call this function from
# either main or subfile's body (i.e. not from inside a function or method)
import main
main.mylist.append("hey")
Using from your_file import * should fix your problems. It defines everything so that it is globally available (with the exception of local variables in the imports of course).
for example:
##test.py:
from pytest import *
print hello_world
and:
##pytest.py
hello_world="hello world!"
Hai Vu answer works great, just one comment:
In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:
# settings.py
def init(arg):
global myList
myList = []
mylist.append(arg)
# subfile.py
import settings
def print():
settings.myList[0]
# main.py
import settings
settings.init("1st") # global init before used in other imported modules
# Or else they will be undefined
import subfile
subfile.print() # global usage
Your 2nd attempt will work perfectly, and is actually a really good way to handle variable names that you want to have available globally. But you have a name error in the last line. Here is how it should be:
# ../myproject/main.py
# Import globfile
import globfile
# Save myList into globfile
globfile.myList = []
# Import subfile
import subfile
# Do something
subfile.stuff()
print(globfile.myList[0])
See the last line? myList is an attr of globfile, not subfile. This will work as you want.
Mike
I just came across this post and thought of posting my solution, just in case of anyone being in the same situation as me, where there are quite some files in the developed program, and you don't have the time to think through the whole import sequence of your modules (if you didn't think of that properly right from the start, such as I did).
In such cases, in the script where you initiate your global(s), simply code a class which says like:
class My_Globals:
def __init__(self):
self.global1 = "initial_value_1"
self.global2 = "initial_value_2"
...
and then use, instead of the line in the script where you initiated your globals, instead of
global1 = "initial_value_1"
use
globals = My_Globals()
I was then able to retrieve / change the values of any of these globals via
globals.desired_global
in any script, and these changes were automatically also applied to all the other scripts using them. All worked now, by using the exact same import statements which previously failed, due to the problems mentioned in this post / discussion here. I simply thought of global object's properties being changing dynamically without the need of considering / changing any import logic, in comparison to simple importing of global variables, and that definitely was the quickest and easiest (for later access) approach to solve this kind of problem for me.
Based on above answers and links within I created a new module called global_variables.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
#
# global_variables.py - Global variables shared by all modules.
#
# ==============================================================================
USER = None # User ID, Name, GUID varies by platform
def init():
""" This should only be called once by the main module
Child modules will inherit values. For example if they contain
import global_variables as g
Later on they can reference 'g.USER' to get the user ID.
"""
global USER
import getpass
USER = getpass.getuser()
# End of global_variables.py
Then in my main module I use this:
import global_variables as g
g.init()
In another child imported module I can use:
import global_variables as g
# hundreds of lines later....
print(g.USER)
I've only spent a few minutes testing in two different python multiple-module programs but so far it's working perfectly.
Namespace nightmares arise when you do from config import mySharedThing. That can't be stressed enough.
It's OK to use from in other places.
You can even have a config module that's totally empty.
# my_config.py
pass
# my_other_module.py
import my_config
def doSomething():
print(my_config.mySharedThing.message)
# main.py
from dataclasses import dataclass
from my_other_module import doSomething
import my_config
#dataclass
class Thing:
message: str
my_config.mySharedThing = Thing('Hey everybody!')
doSomething()
result:
$ python3 main.py
Hey everybody!
But using objects you pulled in with from will take you down a path of frustration.
# my_other_module.py
from my_config import mySharedThing
def doSomething():
print(mySharedThing.message)
result:
$ python3 main.py
ImportError: cannot import name 'mySharedThing' from 'my_config' (my_config.py)
And maybe you'll try to fix it like this:
# my_config.py
mySharedThing = None
result:
$ python3 main.py
AttributeError: 'NoneType' object has no attribute 'message'
And then maybe you'll find this page and try to solve it by adding an init() method.
But the whole problem is the from.
I have 2 files:
Main.py
from test import test
def main():
sol = 'hello'
if test() == sol:
print('Yes')
else:
print('No')
test.py
def test():
return 'hello'
Is there a way to access the sol variable in my test function which is in another file? I'd like to do something like this:
def test():
return sol
This way it's always the same as the variable in Main.py. I tried a solution which is mentioned on Python extract variables from an imported file but it didn't work for me. Thank you for any help
Edit: I'd like to do it without changing the Main.py file
Since sol isn't defined in the function you will need to declare it as a global function so it can be used in the function. Change test.pyto the following...
test():
global sol
return sol
Hope that helps.
If sol is a constant (i.e. a variable which will not change during the course of the program), then you can put it into a separate file, say var.py, and import it into both main.py and test.py:
from var import sol
BUT what you will be importing is a copy of the variable with the value it had at the time it was imported - any subsequent reassignments will not update the value of sol in test.py and main.py. Because a string is immutable, when you reassign a value to it what you are actually doing is you are reusing the variable name for a new entity.
What you need to do is have your variable in a mutable structure, such as a list or a class, so your var.py will look like this:
class v(object):
sol = 'Hello'
and then in main.py and test.py you can refer to sol using:
from var import v
print(v.sol)
This way, any changes to v.sol will be correctly reflected anywhere class v is imported. A bit cumbersome, but that's how it is in Python.
You can use inspect module to get the sol variable from main function without change anything of main.py. Of course, you need to call main function.
Main.py:
from test import test
def main():
sol = 'hello'
if test() == sol:
print('Yes')
else:
print('No')
main()
test.py:
import inspect
def test():
frame = inspect.currentframe()
sol_from_main = 'default'
try:
sol_from_main = frame.f_back.f_locals['sol'] # line A
except:
print('No sol found')
print(sol_from_main) # this print 'hello'
return sol_from_main
Output:
hello
Yes
Explanation:
From the python doc, we can see next:
frame
f_back | next outer frame object (this frame’s caller)
f_locals | local namespace seen by this frame
So line A get the caller of current function, that is main function, and use f_locals to get all local variables of main function, so it can get the sol value from main. FYI in case you still need it.