I've been reading a Python textbook, and I see the following code:
class Database:
# the database implementation
pass
database = None
def initialize_database():
global database
database = Database()
Now, why is there a global declaration inside initialize_database function? We had defined database outside the function, doesn't it make it global already?
Best Regards,
You can reference a global when it's not declared global in a function, but you can only read it; writing it will create a new local variable hiding the global variable. The global declaration makes it able to write to the global.
'global x' doesn't make x global, it should be read as "from now on in this namespace, treat all references to x as as references to x in a higher namespace."
Remember you're not permanently doing anything to x, your just making x point to something different within a function.
Related
For example if I write
a=1
def func():
return a
func()
It will return 1. Is this normal behavior? Are variables supposed to act in a global way in python?
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
That is the way python language works !
Just a beginner question about local and global scope in python
X = 100
#is X a global variable?.We defined it outside the function scope
def foo():
print(X)
return X
#it prints 100 and even returns it
def foo():
X = X + 10
#local error
#UnboundLocalError: local variable 'X' referenced before assignment
def foo():
global X
# if X is a global variable why specify again?
X = X + 10
return X
To modify global copy of a variable you need the to use the global keyword, but you don't need global if you are only accessing that.
from the python website:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
this means that you can access a global variable inside a function without a global keyword. if you want to change it though, you must use the global keyword beforehand.
global and nonlocal are very strange things when I was a beginner.
Just think about it: why do we need them in Python?
It is because we don't need var, let and such similar things to declare variables.
Think about Javascript, it is dynamic script language too and very alike to python, but it needs var or let or const to declare variables.
The most important thing of declaring variables is to determine scope.
So, in Python, our variables have implicit default scope: current scope where they are defined, and if we want to change scope of some variables, we need use global or nonlocal explicitly .
All names on the left side of = mean to define variables.
Before executing code of some certain scope, Python will pre-compute all local variables, which are those on the left side of =. This is why you got UnboundLocalError: local variable 'X' referenced before assignment in:
def foo():
X = X + 10
So, if we look up those names not in defined current scope, just
follow the rules of scope chain: up, up, up and until built_in.
Remember: scope of any name on the left side of = is default current scope, and you have to assign it(bind something to it) before referring it.
How do you dynamically set variables as global in Python 3 functions?
Something like this:
def func1(i):
global i
#Some operation on i
How would I get the global variable to set whatever pre-existing variable is passed into the function? Such that:
func1(foo)
Would preform the operation on the variable foo globally rather than creating a new global variable called i?
If I got it right, your problem is:
I've bound a name to some object at module level; now I want to write a function that changes the binding of that global name to another object passed as an argument to the function.
In Python global names can be referenced inside a function (provided that you don't bind another object to the same name), but to change their binding you must first declare those names as global. The reason is simple: by default all names bound inside a function have function scope.
GLOBAL_NAME = 12
ANOTHER_GLOBAL_NAME = 50
def func(value):
global GLOBAL_NAME
GLOBAL_NAME = value
print(GLOBAL_NAME, ANOTHER_GLOBAL_NAME)
When you call func(33), GLOBAL_NAME will be bound to the object 33. ANOTHER_GLOBAL_NAME is just a reference to a global name; since that name is not bound inside the function, Python look for that name in the global scope.
For further insights on Python scope enclosing you can refer to the Python documentation on the global statement, to PEP-0227 and to PEP-3104.
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.
I am having troubles using global variables in python...
In my program, i have declared 2 global variables,
global SYNC_DATA and
global SYNC_TOTAL_SIZE
Now in one of my functions, I am able to use the global variable SYNC_DATA without declaring it as global again in the function; however , I am not able to use the other global variable SYNC_TOTAL_SIZE in the same way. I have to declare the latter as global in the function again to use it. I get this error if i use it without declaring as global in the function - "UnboundLocalError: local variable 'SYNC_TOTAL_SIZE' referenced before assignment"
Why is it so that sometimes I can access global variables without declaring them as global in functions and sometimes not?
And why Is it that we have to again declare it as global in the function when it is already declared once in the beginning... Why doesn`t the function just check the variable in the global namespace if it does not find it in its namespace directly?
Assuming SYNC_TOTAL_SIZE is not declared as local variable. It depends on what operations you are performing on global variables, for just reading the global variable there is no need to declare it as global, but if you are modifying the value of global variable you have to declare it with global.
Because SYNC_TOTAL_SIZE is probably used somewhere else in that code as non-global, which makes Python find it and think it isn't global. Another reason may be that you just read it in some function and so it doesn't need a global declaration (see this question for more details). For an exact diagnosis, post a minimal code snippet that demonstrates your problem.
The advice is to always say global when you mean it.