Conditionally modify global variable - python

I'd like to do something like this, but I get a SyntaxWarning and it doesn't work as expected
RAWR = "hi"
def test(bool):
if bool:
RAWR = "hello" # make RAWR a new variable, don't reference global in this function
else:
global RAWR
RAWR = "rawr" # reference global variable in this function
print RAWR # if bool, use local, else use global (and modify global)
How do I get this to work? Passing in True or False modifies the global variable.

You cannot. Within a scope, a specific name refers either to a local variable, or to a non-local (e.g. global, or from an outer function) variable. Not both. The global RAWR line makes RAWR a global for the entire scope (that's why you get a warning, it doesn't do what you think it does), just like assignment to a variable makes it local for the entire scope. Edit: Thanks to veredesmarald, we now know it is in fact a syntax error in Python 2. This half of my answer only applies to Python 3 apparently.
You should just use a differently-named local variable, and in the branch where you want to "promote" it to a global, set the global and the local variable. (Or just don't use globals at all.)

The only easy way you can go would be
RAWR = "hi"
def test(newone):
if newone:
lR = "hello" # make RAWR a new variable, don't reference global in this function
else:
global RAWR
lR = RAWR # reference global variable in this function
print lR # if bool, use local, else use global (and modify global)
# modify lR and then
if not newone:
RAWR = lR
Another way, however, could be to abuse the concept of classes and objects to your purposes.
class store_RAWR(object):
RAWR = "hi"
def __init__(self, new): self.RAWR = new
def test(newone):
if newone:
myR = store_RAWR("hello") # get a (temporary) object with a different string
else:
myR = store_RAWR # set the class, which is global.
# now modify myR.RAWR as you need
But this requires other program parts which use the global name to be changed as well.

Related

How can I refer to variable as global in python

I was define a global variables which I wanted to change / give an actual value in a function.
When I tried to run it, I had an error message that informing the global variable is undefined.
please support, thanks. this is my code:
script_name = 'R2M_delayer.py'
recipe_name = 'R2M_E2E_delayer_NR_Ver_5.1'
global images
global metrology_images
logged_date = str(datetime.datetime.now()).split()[0]
NR_log = 'NR_' + logged_date + '.log'
images_output_dir_path = '/usr/local/insight/results/images/toolsDB/lauto_ptest_s' + str(datetime.datetime.now()).split()[0] + '/w3'
metro_images_dir_path = find_dir_path_delayer.get_delayer_images_dir_path()
metro_callback_dir_path = '/usr/local/disk2/unix_nt/R2M/RecipeRun'
def images_check():
estimated_num_of_images = 6640 # Hard codded for Sanity wafer #3
Actual_Images_List = os.listdir(images_output_dir_path)
images = len(Actual_Images_List)
if images >= estimated_num_of_images or images < 7000:
return True, images
print("\nImages quantity is not equal to the actual images in results folder.\n")
return False
print(' ' + str(images) + ' images were send.\n')
Problem has solved. I defined my global variables as fields in class and I was revalued that values of the fields in the functions.
The global keyword goes inside the function. That allows you to call that variable outside the function. If you declare the variable outside the function, you don't need it. By the way, you're returning images anyway. It is much better to return the value instead of modifying global variables, because it may return its reference instead. Global variables are not a good practice because it can """mess up""" with your allocated local memory for your program. I recommend using the garbage collector library gc.collect() to collect any data of a global variable you are not using or managing.
Declare global variables inside function definition, otherwise the scope of variables in function is always local.
To avoid "variable is not defined" error you can initiate them in the main code with some default value, e.g., images = None.
Agree with previous answer, try to not use global variables.

When is the global statement necessary?

I am a little confused about "global" statement.
"sample code 1" runs ok without using "global" statement; however, "sample code 2" will not run unless the "global a" is un-commented.
Why do I have to declare "global" in "sample code 2" but not in "sample code 1"?
# sample code 1
def updating():
a.append(1);
if __name__=='__main__':
a=[100];
print(f'before updating, variable a id is {id(a)}, and value is {a}')
updating()
print(f'after updating, variable a id is {id(a)}, and value is {a}')
# sample code 2
def updating():
#global a
a=a+[1]
if __name__=='__main__':
a=[100];
print(f'before updating, variable a id is {id(a)}, and value is {a}')
updating()
print(f'after updating, variable a id is {id(a)}, and value is {a}')
By default, an assignment to a name always operates on a local variable, creating a new one if it is not currently defined.
The global statement makes the name refer to a variable in the global scope, permitting you to assign to a global name without creating a new local variable.
(The nonlocal statement does something similar, except it makes the name refer to a variable defined in the closest enclosing scope, which is not necessarily the global scope.)
In your first example, you are not assigning to a name; you are performing attribute lookup on a free variable, which resolves to the global variable of the same name.
In your second example, you try to create a new local variable. Since scope is determined at compile time, a = a + [1] will fail, because the a on the right-hand side will still refer to the as-of-yet undefined local variable a. With global, the assignment does not create a local variable, so the right-hand side is an expression involving the global variable, and the result is assigned to the global name as well.

get and set value in python

I want to have few global variables in my python code.
Then set their values with set function and want to get their values through get function.
For example:
a = None #global variable1
b= None #global variable2
def set(var, value):
var = value
def get(var):
return var
set(a, '1')
get(b, '2')
I want to have a generic get and set function which will do this for any global variable. How can I do this in python ? The code written here gives error.
If you're willing to pass the variable names as strings, you can do this using the globals() function. But even though you can, I don't think it's a good idea.
First, here's how you could do it:
def get_var(var_name):
return globals()[var_name]
def set_var(var_name, value):
globals()[var_name] = value
I'm not using the name set since that's a builtin type, which you probably don't want to shadow with something else.
You'd call it like:
set_var("foo", 1)
bar = get_var("foo")
print(foo, bar) # prints 1 1
So it works, but there's really no need for those functions. You can assign or fetch global variables using normal syntax instead. Just use foo = 1 instead of set_var("foo", 1) (if you're doing it in a function, put global foo first). Getting a global variable is as simple as naming it (like I do in print(foo)).
If you don't know the variable name ahead of time, you should probably be putting the name and value into a dictionary, rather than making them global variables. Variable names are for the programmer to use. They're not data!
Python is "call by value" not "call by reference". Meaning when you call "set(a, '1')", you are passing the value of "a" to the function "set". The variable "var" in "set" is a local variable to the function itself and will not effect your global variable "a". You need to give your setter and getter methods access to your global variables. You can do this by making them all part of a class object.

Python: Understanding global a little bit more

I have a program in python. part of the program is:
suggestengines = get_suggestengines(suggestengines)
sleeptimer = sleepcount * len(suggestengines)
seeds = get_seeds(dummydata=False)
For further programming I want to make a function of it:
def first_step():
suggestengines = get_suggestengines(suggestengines)
sleeptimer = sleepcount * len(suggestengines)
seeds = get_seeds(dummydata=False)
Now I get an error for "suggestengines" that I want to pass into get_suggestengines(). Also sleep timer and seeds get a marker, that I don't use them in the rest of the program. I googled it and got the answer: Us global. So I added global for everything
def first_step():
global suggestengines
global sleeptimer
global seeds
suggestengines = get_suggestengines(suggestengines) #which engines to run?
sleeptimer = sleepcount * len(suggestengines)
seeds = get_seeds(dummydata=False)
In further part of the program I have
for seed in tqdm(seeds, leave=True):
there the program gives me an error vor seeds in tqdm. If I change it to also make a def of it like:
def partTwo():
for seed in tqdm(seeds, leave=True):
Then I don't get an error anymore although I didn't used global. Can someone explain me why and if I need to use global in part 2 also?
The statement
global <identifier>
tells python that <identifier> should refer to a global when used in assignments. This is necessary in functions that change globals because Python has no syntactical difference between declaring a variable and assigning to an existing variable. The default in python is to have assignments in functions create new variables, rather than change global state.
When you just read from a variable there is no syntactic ambiguity, so Python will just use whatever variable it finds (i.e. global if there is no local one).
Example:
a = 1
def foo():
a = 2 # this will create a new, local variable a
def bar():
global a # "when I refer to a, I mean the global one"
a = 2 # this will change the global variable a
If no global with the specified name exists, the global statement itself will not create a new global variable, but any following assignment will. E.g. given the following:
def x():
global c
def y():
global c
c = 1
def z()
print c
x(); z() would be an error(global name 'c' is not defined), while y(); z() would print 1.
seeds hasn't been initialized yet by the time the for loop is hit, since its initialization is part of a def that hasn't been called yet. If you put the for loop inside a def then it will be called in the order you call the functions, so the interpreter won't complain until you actually use it.
The only thing to keep in mind here is this: use variables after they have been initialized.

getting around immutable string python

Ok, I started coding this:
lastentry = 'first'
campdata = {'a1'=0,
'b2'=0}
class Someclass:
def on_window1_destroy(self, widget, data=None):
print campdata
def func1(self)
lastentry = 'b2'
def func2(self)
lastentry = 'a1'
def func2(self)
campdata[lastcall] +=1
But then I found out that python strings (and integers) were immutable...
So how do I get around ths?
I guess your problem is that you want to change the value of the global variable lastentry by calling func1 or func2, which doesn't work. The reason it does not work is because the variable is in the global scope, and assigning to the same name inside of a function just creates a local variable with the same name as the global one. To assign to a global variable, you need to declare it as such:
lastentry = "something"
def func1():
global lastentry #tell python to treat references to lastentry as global
lastentry = "somethingelse"
Note that you don't need to do this if all you are doing with the global value is reading it like in your third function. But if you assign to a variable, it is treated as local to its scope - which is normally the surrounding function - if you don't explicitly declare it global (or nonlocal in python3).
Global variables should only be used when neccessary as they add complexity to the code. In your case you can probably refactor your code to use an instance variable or class variable for lastentry instead of a global one.
Like others have said, there doesn't seem to be any attempt to modify a string in your code, so that's hardly the problem.
That said, lastcall looks random, should it perhaps be lastentry?
I don't see any problem with your code (except for some details). String immutability does not seem to be a problem, here.
You may want to write, instead of the code in your question:
campdata = {'a1': 0, # Not "= 0"
'b2': 0}
and
campdata[lastentry] +=1 # not "lastcall"
Also, as l4mpi mentioned, you need a global lastentry in the methods where it is modified.
Another point: relying on global variables is quite unusual. If at all possible, it would be best to use instance attributes (self.campdata, self.lastentry).

Categories

Resources