This question already has answers here:
Visibility of global variables in imported modules
(9 answers)
Closed 3 years ago.
main1.py
import mya
a=10
mya.increment_a()
a=a-5
print(a)
module mya.py
def increment_a():
global a
a=a+1
print(a)
name 'a' is not defined.
I don't understand why. I declare variable a as global in module, so from this point a=0 as it is in mail1.py
upd: I need work globaly. Starting value for variable "a" set in main.py, function in module mya.py will edit "a", and return new value to main.py for further use.
--- closed topic---
Now I use "arguments" and "return" and in work:
mya.py
def increment_a(a):
a=a+1
print(a)
return a
main1.py
import mya
a=0
print(a)
a=mya.increment_a(a)
a=a+10
print(a)
From Visibility of global variables in imported modules:
Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)
One approach to deal with it is:
import mya
mya.a=3
mya.increment_a()
Related
This question already has answers here:
How do I use global variables in python functions? [duplicate]
(7 answers)
Closed 5 years ago.
Im trying to use global variables in order to declare them at the start of my code just like you would in C# however when ever i edit them in a function and i try call it in another function it throws an error saying that the variable is not declared?
This is where i declare the variables:
from tkinter import *
import os
global Name
global Wmain
global directory
global Username
global Password
global Code
This is where i change the the directory variable:
def NameGet():
Name = NameEntry.get()
directory = ('C:\\Users\\Bradley\\Desktop\\Log In system\\Members\\' + Name + '.txt')
CheckFile(Name)
This is where i am getting the error:
def SignUpFinished():
with open(directory, W) as F:
F.write(Username)
F.write(Password)
F.write(Code)
F.close()
Now i feel im either making a really novice mistake or something isnt working right with my code. any ideas?
In order to use global variable you need to explicitly set it inside a method.
For example:
a=4
def func():
global a
print(a)
func()
This question already has answers here:
Visibility of global variables in imported modules
(9 answers)
Closed 7 years ago.
It appears that a class defined in a script has a different scope to one that is imported into the script. For example:
In a file foo.py:
class foo(object):
def __init__(self):
print globals()
In my main file:
from foo import foo
class bar(object):
def __init__(self):
print globals()
classimport = foo()
classinternal = bar()
The list of globals returned from foo and bar are different - why is this?
It is making life difficult as any class that needs to access the main globals() has to reside in the main file. How do I ensure that the imported class has the same global scope? Some things that I have tried after reading other posts here and here include:
module = __import__("foo", fromlist="foo")
globals()["foo"] = getattr(module, "foo")
and
__builtin__.foo = foo
Any help appreciated!
[EDIT] ---
So per the link above, this is answered in a duplicate article. It turns out that scope is not shared across modules. It mentions several ways around this, but in my case I need to actually create / read / write global variables. So I created a routine in the main script and pass it as an object when foo and bar are initialized. For example:
def PrintGlobals():
print globals()
class bar(object):
def __init__(self, PrintGlobals):
self.PrintGlobals = PrintGlobals
self.PrintGlobals()
classinternal = bar(PrintGlobals)
(Not my choice of how all this should work, its a hack until I get some time with the application devs :-)
Here's what the Python 3 FAQ has to say:
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.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
To see globals in various scopes, try doing a print(globals()) at various points during your execution. For example: at the top-level module before any code is run, then in __init__.py if you have any code in there (because you import foo), at foo's module level, within each function, and before/after you modify any variables passed to the function.
This answer further explains:
I think the key thing you're missing here is that each module has its own "global" namespace. This can be a bit confusing at first, because in languages like C, there's a single global namespace shared by all external variables and functions. But once you get past that assumption, the Python way makes perfect sense.
Note however that all names assigned in a package __init__.py file are available in the package namespace when you import the package or a module in the package.
This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 8 years ago.
I need to create a variable in a different script from the main one in my game I am working on, with Python and Pygame.
For example:
def test():
a = 10
def testing():
return a
Then I run code like this:
import (script name)
script name.test()
script name.testing()
And after this, it gives an error. How can I fix this problem?
'a' in testing() is not a global variable and hence it's not recognised from previous function test(). If you really want to use 'a' from test() then you can probably define 'a' as Global Variable.
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 4 years ago.
How can I define a global variable.
For example I have Foo1 class and Foo2 class and I want to use FooVariable in this classes as a global variable.
If you wanted a global variable named foo, you would just have to put global foo at the top of any function in which it is used. For example,
def do_something():
global foo
foo = foo + 1
print foo
Note that Python "global" variables are only global to the module they appear in, not global to the entire program (as in some languages).
first.py
myGlobal = "hello"
def changeGlobal():
myGlobal="bye"
second.py
from first import *
changeGlobal()
print myGlobal
The output I get is
hello
although I thought it should be
bye
Why doesn't the global variable myGlobal changes after the call to the changeGlobal() function?
Try:
def changeGlobal():
global myGlobal
myGlobal = "bye"
Actually, that doesn't work either. When you import *, you create a new local module global myGlobal that is immune to the change you intend (as long as you're not mutating the variable, see below). You can use this instead:
import nice
nice.changeGlobal()
print nice.myGlobal
Or:
myGlobal = "hello"
def changeGlobal():
global myGlobal
myGlobal="bye"
changeGlobal()
However, if your global is a mutable container, you're now holding a reference to a mutable and are able to see changes done to it:
myGlobal = ["hello"]
def changeGlobal():
myGlobal[0] = "bye"
I had once the same concern as yours and reading the following section from Norman Matloff's Quick and Painless Python Tutorial was really a good help. Here is what you need to understand (copied from Matloff's book):
Python does not truly allow global variables in the sense that C/C++ do. An imported Python module will not have direct access to the globals in the module which imports it, nor vice versa.
For instance, consider these two files, x.py,
# x.py
import y
def f():
global x
x = 6
def main():
global x
x = 3
f()
y.g()
if __name__ == ’__main__’:
main()
and y.py:
# y.py
def g():
global x
x += 1
The variable x in x.py is visible throughout the module x.py, but not in y.py. In fact, execution of the line
x += 1
in the latter will cause an error message to appear, “global name ’x’ is not defined.”
Indeed, a global variable in a module is merely an attribute (i.e. a member entity) of that module, similar to a class variable’s role within a class. When module B is imported by module A, B’s namespace is copied to A’s. If module B has a global variable X, then module A will create a variable of that name, whose initial value is whatever module B had for its variable of that name at the time of importing. But changes to X in one of the modules will NOT be reflected in the other.
Say X does change in B, but we want code in A to be able to get the latest value of X in B. We can do that by including a function, say named GetX() in B. Assuming that A imported everything from B, then A will get a function GetX() which is a copy of B’s function of that name, and whose sole purpose is to return the value of X. Unless B changes that function (which is possible, e.g. functions may be assigned), the functions in the two modules will always be the same, and thus A can use its function to get the value of X in B.
Python global variables are not global
As wassimans points out above they are essentially attributes within the scope of the module they are defined in (or the module that contains the function that defined them).
The first confusion(bug) people run into is not realizing that functions have a local name space and that setting a variable in a function makes it a local to the function even when they intended for it to change a (global) variable of the same name in the enclosing module. (declaring the name
in a 'global' statement in the function, or accessing the (global) variable before setting it.)
The second confusion(bug) people run into is that each module (ie imported file) contains its own so called 'global' name space. I guess python things the world(globe) is the module -- perhaps we are looking for 'universal' variables that span more than one globe.
The third confusion (that I'm starting to understand now) is where are the 'globals' in the __main__ module? Ie if you start python from the command line in interactive mode, or if you invoke python script (type the name of the foo.py from the command shell) -- there is no import of a module whose name you can use.
The contents of 'globals()' or globals().keys() -- which gives you a list of the globals -- seems to be accessible as: dir(sys.modules['__main__'])
It seems that the module for the loaded python script (or the interactive session with no loaded script), the one named in: __name__, has no global name, but is accessible as the module whose name is '__main__' in the system's list of all active modules, sys.modules