I cannot quite find a good description on how import works when importing your own files.
I was having trouble importing a file with a global variable and managed to get it to work when I put the global variable just before the files main function.
Can someone explain why it works this way?
A quick run down on how import actually works.
It did not work when I did this (pseudocode):
file1:
import file2
file2.main()
file2:
main():
glob_var = 0
def add():
global glob_var
glob_var += 1
add()
But worked if I put the variable first like this:
file1:
import file2
file2.main()
file2:
glob_var = 0
main():
def add():
global glob_var
glob_var += 1
add()
'main' is just a method. Variable inside a method is local by definition. Thats why 2nd way is working.
The reason it didn't work is because you are declaring the global variable inside of main. (you did miss the colon after definition of main which makes it confusing but looking at the indentation I suppose it's a definition). Global variables have to be defined outside the scope of any local function. This is a case of nested function definition.
You can do without global variables as well if that's what you are looking for. If however you want to use the variable defined in main inside a nested function then you can do the following:
In python 3 there is a way to get this thing done however using the nonlocal keyword
def main():
var = 10
def nested_fun():
nonlocal var
var = var + 1
As you see we do not need a global variable here.
Edit: In case of python 2 this does not work. However you can use a list in the main and modify that list inside nested function.
def main():
var = [10]
def nested_fun():
nonlocal var
var[0] = var[0] + 1
If I understand the question correctly, it's regarding the global variable and have nothing to do with importing.
If you want to define a global variable, it has to be defined in module level. The main function is not the global scope, that's why the first code does not work as expected. By moving the variable declaration outside of main, it would be defined in global scope, so the add method can access it using as a global variable.
I think we have to begin with what global statement means. From the docs:
It means that the listed identifiers are to be interpreted as globals.
The important point is it's only about interpretation, i.e. global does not create anything. This is the reason, why your first example does not work. You are trying to add +1 to something not existing. OTOH, global_var = 100 would work there and it would create a new global variable.
Related
I was just playing around with Python and I came across something interesting which I didn't quite understand. The code goes as follows:
a = 1
def function():
print(a)
function()
print(a)
Here, a is a global variable and I used it in my function and the result was:
1
1
I was able to use a global variable locally in my function without having to use global a in my function.
Then, I experimented further with this:
a = 1
def function():
a = a+1
print(a)
function()
print(a)
When I ran this code, an error showed up and it said that the local variable a was referenced before assignment. I don't understand how before it recognized that a was a global variable without global a
but now I need global a like this
a = 1
def function():
global a
a = a+1
print(a)
function()
print(a)
in order for this code to work. Can someone explain this discrepancy?
You can read the value from a global variable anytime, but the global keyword allows you to change its value.
This is because when you try and set the a variable in your function, by default it will create a new local function variable named a. In order to tell python you want to update the global variable instead, you need to use the global keyword.
When creating "=" ,a new variable inside a function python does not check if that variable is a global variable, it treats that new variable as a new local variable, and since you are assigning it to itself and it does not exist locally yet, it then triggers the error
I am a beginner in python.
I am not understanding why about
assign after define global variable : valid
valid but define and assign global variable at once : not valid.
As for example:
def Test():
global a=15
Test()
print(a)
Is invalid while:
def Test():
global a
a=15
Test()
print(a)
Is valid
The global statement syntax is global <name> and just tells the interpreter that you are working with a variable from globals() instead of locals() for the current scope/frame. It really just tells Python where to grab the variable, and doesn't support assignment.
The global keyword tells your interpreter that a variable is a global one. Let's say you have this code:
a = 10
def p():
a = 20
print('This is a local:', a)
print("a is unchanged:", 10==a)
def q():
global a
a = 40
print('This is the global:', a)
print("a has changed:", 40==a)
Remember, the global only tells your interpreter that "There's this variable outside your local variables" when it is called inside functions. Therefore, you cannot assign a value to a variable that you are calling as global in one line.
I'm new to python as well, so I suppose I'll work this out with you! It looks like it indicates a syntax error at the = sign in line 2. It works in the second example because you declared the variable separately on a new indented line below global? So I'm guessing the first example won't work because the variable is declared along with global?
I want to define a Python function doing:
1. Check if a variable already exist.
2. If not, create it as a global variable (because I want to use it outside the function).
def foo():
try:
x
except NameError:
global x
x = 1
else:
pass
foo()
print(x)
Then there is an error:
SyntaxError: name 'x' is used prior to global declaration
How to solve this? Thank you :)
Something like this could work.
def foo():
if not('x' in locals()):
global x
x = 1
foo()
print(x)
just check if the x variable exists.
you could also check if a variable is declared as global
if not('x' in globals()):
Just declaring a variable as global at the top of your function won't create it - so this form works:
def foo():
global x
try:
x
except NameError:
x = 1
The key thing to understand here is that when Python compiles a function, it "bakes" each variable inside the function as either a local, nonlocal, or a global (or builtin) variable - any access to that variable will have either one or the other relevant bytecode. The "global" declaration thus affects the whole function, regardless of were it is - and since tryig to access a variable before the global statement would look ambiguous, the error you saw is forced.
But since you are at it - are you sure you want to do it?
global variables are good for having values that can be shared in functions in a module - but then, even if they are to be initialized in the call to an specific function, they should be declared in the module body, and properly documented. If you can't have the final value at module load time, just assign it to None.
How can I assign a function argument to a global variable with the exact same name?
Note:
I can't do self.myVariable = myVariable because my function is not inside of a class.
When write the following code, I get an error saying that "argument is both local and global."
myVar = 1
def myFunction(myVar):
global myVar
Is this impossible? and if so is it uncommon in other languages? Coming from java I'm used to this.myVar = myVar
Edit I already know that I can rename the variable. That's the easy way out.
Best solution: refactor your code. Rename something, or use an object with object properties instead of a global variable.
Alternative, hacky solution: modify the global variable dict directly:
my_var = 1
def my_function(my_var):
globals()['my_var'] = my_var
The answer is to trick Python into doing it. In your code:
myVar = 1
def myFunction(myVar):
global myVar
myFunction is never run (you never call it). So, the script never gets to the global myVar point. Yet, Python still blows up for some reason. I believe that that is because it has been told "Don't allow this". Regardless, you can trick it into doing what you want. One way that hasn't been suggested is to use a simple function in myFunction:
myVar = 1
def myFunction(myVar):
def trick(arg):
global myVar
myVar = arg
trick(myVar)
print myVar # Comes back with 1
myFunction(22)
print myVar # Comes back with 22
May not be on one line, but you don't have to import anything and it is easier to read.
The best (and fastest) thing to do would be to take the easy way out and rename the variable(s). But if you insist, you could get around the naming conflict with this:
import sys
_global = sys.modules[__name__]
# or _globals = sys.modules[__name__].__dict__
myVar = 1
def myFunction(myVar):
_global.myVar = myVar # or _globals['myVar'] = myVar
print myVar # 1
myFunction(42)
print myVar # 42
Explanation:
Within a module, the module’s name (as a string) is available as the value of the global variable__name__. The namesys.modulesrefers to a dictionary that maps module names to modules which have already been loaded. IfmyFunction()is running, its module has been loaded, so at that timesys.modules[__name__]is the module it was defined within. Since the global variableMyVaris also defined in the module, it can be accessed using sys.modules[__name__].myVar. (To make its usage similar to java, you could name itthis-- but personally I think_globalis a better.)
In addition, since a module’s read-only__dict__attribute is its namespace -- aka the global namespace -- represented as a dictionary object,sys.modules[__name__].__dict__ is another valid way to refer to it.
Note that in either case, new global variables will be created if assignments to non-existent names are made -- just like they would be with the global keyword.
So I am trying to declare the variable "checks" as a global variable because I get the following issue:
File "C:\Python27\Projects\Automatic Installer\autoinstall.py", line 11, in installFunc
if checks[0] == 1:
NameError: global name 'checks' is not defined
Here's my code, I've tried to add global checks to both the main body of the program as well as the installFunc function. Is there another location I should be adding it/some other way to indicate that checks should contain the information in the program?
import urllib
import subprocess
from Tkinter import *
global checks
def installFunc():
global checks
subprocess.call("md c:\MGInstall", shell=True)
subprocess.call (u"net use w: \\it01\files")
if checks[0] == 1:
subprocess.call(u"w:\\software\\snagitup.exe")
if checks[1] == 1:
subprocess.call(u"w:\\software\\camtasia.exe")
if checks[2] == 1:
urllib.urlretrieve(u"SUPERLONGURLLOLOLOL", u"c:\\MGinstall\\gotomeeting.exe")
subprocess.call (u"c:\\MGinstall\\gotomeeting.exe")
urllib.urlretrieve(u"http://ninite.com/.net-7zip-air-chrome-cutepdf-dropbox-essentials-firefox-flash-flashie-java-klitecodecs-quicktime-reader-safari-shockwave-silverlight-vlc/ninite.exe", u"c:\\MGinstall\\MGinstall.exe")
subprocess.call (u"c:\\MGinstall\\MGinstall.exe")
subprocess.call (u"w:\\printers\\installer\\printer.exe")
app = Tk()
w = Label(app, text="CompanyName IT Automatic Installer")
w.pack()
text = ["Snagit", "Camtasia", "GotoMeeting"]
variables = []
for name in text:
variables.append(IntVar())
Checkbutton(text=name, variable=variables[-1]).pack()
b = Button(text="OK", command=installFunc)
b.pack()
app.mainloop()
checks = [variable.get() for variable in variables]
I think this is because checks gets set after the mainloop (the last line of the posted code). the function installFunc gets called from the mainloop via a button press, but checks hasn't been defined yet.
Using the global data in this case isn't a good idea anyway. You should probably do something like:
def installFunc(checks):
...
checks = [variable.get() for variable in variables]
b = Button(text="OK", command=lambda : installFunc(checks))
Or, even better, wrap all this up in a class... that way you can do:
self.b=Button(..., command=self.installFunc)
Replace the first 'global checks' (the one at the global level) with 'global = ...', initializing it appropriately. Using 'global' is really relevant only within a function/method. Per the Python docs: The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global. You may want to read this as well - has lots of relevant info: Using global variables in a function other than the one that created them
The problem is not the first 'global checks'. What causes the error is that checks is accessed before it is initialized.
You must initialize checks before calling the main loop of the application.
First of all, Python is not PHP.
You need to use keyword global if an only if, you're going to assign to global variable within scope of a function.
global checks at top level makes no sense at all, and more importantly does not define that variable.
global checks in your installFunc() does not make sense, as you do not assign anything to that variable, in fact you don't even modify it.
In Python variables from outer scope are visible in local scope, unless of course you try to assign something, which would be interpreted as redefining that variable within local scope.
Problem with your code is that you only define checks after exiting main loop. Correct code would look like this
import urllib
import subprocess
from Tkinter import *
#no global definition here...
def installFunc():
#no global definition here...
subprocess.call("md c:\MGInstall", shell=True)
...
...
#define checks before starting main loop
checks = [variable.get() for variable in variables]
app.mainloop()