Hello. I am trying to use a global dict created in main.py, which is called in functions.py.
In my main.py I have:
import sys,os,...
import functions.py #import my second file
matrix = {}
matrix_do_something
search_the_matrix(value) #which is defined in functions.py
#FILE: functions.py
def search_the_matrix(value):
global matrix
if value in matrix:
return True
else:
return False
and I get this error:
NameError: global name 'matrix' is not defined
I have read a solution on stackoverflow, which says to put everything in a global file and then call from every file global.matrix[value] but I don't want this. I want just call it matrix and think of it as my global matrix. Is this possible?
Thank you in advance
In functions.py you would have to import it
from main import matrix
Though I would want to come up with a better name for my module than main.
If you want an object to be available in a module / file you need to either create it there or import it from somewhere else.
Related
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 am trying to find a way to share a variable between multiple python scripts. I have the following code:
b.py
my_variable = []
a.py
from b import my_variable # import the value
def run():
global x
x = my_variable.append("and another string")
print(my_variable)
if __name__ == '__main__':
run()
c.py
import a
print(a.x)
a.py runs just fine without giving any error. However, when I run the c.py file, it gives off the following error:
Traceback (most recent call last):
File "E:/MOmarFarooq/Programming/Projects/Python Projects/Variables across files/c.py", line 2, in
<module>
print(a.x)
AttributeError: module 'a' has no attribute 'x'
What I want the code to do is, print the new value of my_variable after it has been changed in a.py . Is there any way I can do that?
the error occurred because you never called the run function from a.py. The if __name__=='__main__': statement is only satisfied if you are running a.py as a program, not importing it as a module.
So a.py should be
from b import my_variable # import the value
def run():
global x
x = my_variable.append("and another string")
print(my_variable)
run()
Note that x will be set to None because the append function does not return anything. It just appends a value to a list.
You need to call the run() function in your c.py file.
Here's how the code should be:
import a
a.run()
Well, module 'a' does have no attribute 'x'. Module 'a' has a function that creates a variable 'x', but as long as the method isn't called, the attribute isn't there.
You could change file c.py to:
import a
a.run()
print(a.x)
Another solution would be to make sure that the run() function is always called when importing module 'a'. This is currently not the case, because of the line if __name__ == '__main__':.
If you don't want to run the code but only want to make sure the variable exists, just define it in the module. Before the definition of your run() method, just add x = None (or use any other initial value you prefer).
Note, however, that there other problems with your code and that using globals in this way is a really bad programming pattern, which will likely lead to other problems later on. I wonder what you want to achieve. It probably would be a better solution if you could pass x as argument to the run() function instead of referring to a global variable. But that's outside the scope of this question and difficult to answer without more information.
I'm making a small game and wanted a settings page function that's in a seperate .py file to keep things more clean and easily editable. I have a global variable called textSpeed (which I use the global keyword to use properly in the function) which I change in this runSettings function, but when I print the variable back in my main file it hasn't changed.
The code in the main file (main.py)
from settings import runSettings
textSpeed = "not set"
runSettings()
print(textSpeed)
The code from the settings fuction file (settings.py)
def runSettings():
global textSpeed
textSpeed = input("select text speed. ")
print(textSpeed)
return textSpeed
textSpeed is a local variable - local to the main module.
You need to reference the variable from settings.
import settings
settings.textSpeed = "not set"
runSettings()
print(settings.textSpeed)
To avoid circular import, I advise you to create a third file if you wish to keep it this way. Let's call it varSpeed.py with the following code:
global textSpeed
textSpeed = "not set"
Then you can import varSpeed from both other files have access to that variable without the circular issue.
The runSettings function already retuns the value it sets as well. Instead of messing with mixing namespaces and importing global variables, just use the returned value in main.py:
textSpeed = runSettings()
the problem is that you are trying to change a variable from a different file, while you have not imported the file. I think the easiest way to handle this is to use a class variable like this:
Main file:
from class_file import MyClass
MyClass.run_settings()
print(MyClass.text_speed)
Settings file:
class MyClass:
text_speed = 'n/a'
#staticmethod
def run_settings():
MyClass.text_speed = input("Select text speed: ")
return MyClass.text_speed
My friend asked me to build a function that can execute code in a for loop so, I was doing that and I was using exec in the same file I was declaring a variable name, now when I access name from exec, it says NameError: name 'name' is not defined
This thing is in multiple files, one that runs everything, second that includes all functions and one that calls all functions
I have tried to define variables inside exec and sure, it works.
I have tried Accessing variables in functions.py(File that contains every function) file and it works too.
I have tried merging functions.py and test.py(the file that's using exec) and then running it directly through python and it worked
My functions.py file
def forloop(current, maximum, code):
for x in range(current, maximum):
exec(str(code), globals())
My 'test.py'(It's the one where I call functions)
from functions import *
name = 'Ameer'
forloop(1,3,"""
echo(name)
""")
And, I am running it all through another exec in my 'runner.py'
from functions import *
file = open('test.py', "r+")
content = file.read()
exec(content)
Now, it's giving me an error saying NameError: name 'name' is not defined when it is defined. Please can you guys help me with this issue
You need to use the variables from the place where forloop is called.
import inspect
def forloop(current, maximum, code):
frame = inspect.currentframe().f_back
for x in range(current, maximum):
exec(str(code), frame.f_globals, frame.f_locals)
I have a problem with including a function from another file to main executable script. I have too many functions and my main script became too long and hard to manage. So i've decided to move every function to separate file and than attach/include it. I've read nearly any relative post here to resolve my problem but no luck. Let's see:
main_script.py
==================
from folder.another_file import f_fromanotherfile
class my_data:
MDList=[]
work=my_data()
def afunction():
f_fromanotherfile()
return
and
another_file.py
=====================
#In this file i've put just function code
def f_fromanotherfile():
a=[1,2,3,4]
work.MDList=a
return
And this is the error:
line 11, in f_fromanotherfile
work.MDList=a
NameError: global name 'work' is not defined
Help me please
The scope of 'work' is its module, main_script.py, so you cannot access it from another module. Make 'work' an argument of f_fromanotherfile instead:
In another_file.py:
def f_fromanotherfile(work):
# function body stays the same
In main_module.py:
def afunction():
f_fromanotherfile(work)
because in another_file.py
#In this file i've put just function code
def f_fromanotherfile():
a=[1,2,3,4]
work.MDList=a
return
work is not a global variable.And then doing assignment to it can't work.
u should change ur code to: another_file.py
#In this file i've put just function code
def f_fromanotherfile():
global work
a=[1,2,3,4]
work.MDList=a
return
with the global keyword u can say the variable in so-called global scope and do ur assignment.
PS:kind of like the keyword extern in C?