Update value of a variable in a module - python

I have two files main.py and val.py. A value is taken from val.py in the main file and then I want to update the variable in the original file. Then use that value further in the calculations. Each time when I call the function I want to get the updated value rather than the initial value. But I am only getting the initial value here.
val.py
num = 0
#update the original value
def update(num):
num +=1
return
#get the current 'num' value
def current():
return num
Main.py
import val
val.update(val.current())
print(val.current())
The global variable is not getting updated. I can't seem to figure out the correct issue here. I am passing the values as well in the functions as arguments. It would be really helpful if someone could even give a hint.

In update(), you've shadowed the module's num variable with a local variable that's also called num. If you get rid of it and use the global keyword, you can modify the module's num value.
num = 0
def update():
global num
num += 1

Related

Function takes wrong variable python

I need to change a variable each time the function is called.
My function counts the number of time this function has been called:
def score_chart():
num_of_charts=+ 1
return num_of_charts
At the beginning num_of_charts equals 0. Then I call the function and re-save num_of_charts to be equal 1.
But if I call it second time, the result is still 1, while I m expecting to get 2.
num_of_charts = 0
num_of_charts = score_chart()
print (num_of_charts)
num_of_charts = score_chart()
print(num_of_charts)
1
1
Could you please help
Use a parameter to get the old value.
def score_chart(num):
return num + 1
num_of_charts = 0
num_of_charts = score_chart(num_of_charts)
print(num_of_charts)
num_of_charts = score_chart(num_of_charts)
print(num_of_charts)
A general and useful way to count calls to any function is to define and use a function decorator. The decorator function maintains a count of the calls and this can be accessed whenever required.
def call_counter(func):
def keeper():
keeper.calls += 1
return func()
keeper.calls = 0
return keeper
#call_counter
def score_chart():
pass # function could do anything required
for i in range(4):
score_chart()
print(score_chart.calls)
which prints 4
The statement: My function counts the number of times this function has been called:
def score_chart():
num_of_charts=+ 1
return num_of_charts
is not true. Your function assigns to num_of_charts the value + 1.
What you actually intended to do is to increase the value by one using num_of_charts += 1 but had put the + at the right side of = instead of the left side.
This is the reason why the returned result was always 1.
In addition to this above you need to know that in Python it is important to be aware of the local and global scope of variable names used in a function (check out the docs on it). Not being aware of that leads very often to confusion and wrong expectations. stackoverflow is full of questions which resulted from this kind of confusion.
As long as you only use a variable name in a function it will represent the global value assigned outside of the function before calling it. This is the reason why:
def score_chart_1():
return num_of_charts
is able to return the current value assigned to num_of_charts outside the function so that:
num_of_charts = 2
print(score_chart_1())
num_of_charts = 3
print(score_chart_1())
will print 2 and 3.
If you in your function try to assign a value to a variable name using num_of_charts += 1 the variable name changes its scope from global to local in the function.
Notice that num_of_charts += 1 is equivalent to num_of_charts = num_of charts + 1 and Python needs to know the value of num_of_charts to increase it by one. But usage of the assignment operator = with num_of_charts changed the scope of num_of_charts to local where num_of_charts does not yet have a value and because of that an:
UnboundLocalError: local variable 'num_of_charts' referenced before assignment
will be raised.
The Error can be avoided by declaring the scope of a variable to be global in the function using as first function statement (as first is the usual convention in Python):
global num_of_charts
With this statement above there will be no UnboundLocalError and the function will then work as expected.
Even is this changes will solve your problem this kind of solution is considered to be a bad programming style and the approach of passing a counter parameter to the function and updating it with the return value in order to pass the changed value on next function call a better one (see the answer posted by Barmar for code of this approach).
Best approach to achieve what you want would be to use a Python class where it would easily be possible to count any function calls. See code below for an example of code (choice of variable names should be sufficient as explanations what the code does):
class Charts:
def __init__(self, list_with_charts):
self.list_with_charts = list_with_charts
self.list_with_scores = [0]*len(list_with_charts)
def score_chart(self, chart_index):
return self.list_with_scores[chart_index]
def show_chart(self, chart_index):
# some code to present/show the chart
self.list_with_scores[chart_index] += 1
objCharts = Charts(['chart0.ppt', 'chart1.ppt', 'chart2.ppt'])
objCharts.show_chart(0)
objCharts.show_chart(0)
objCharts.show_chart(2)
objCharts.show_chart(2)
objCharts.show_chart(2)
print(objCharts.score_chart(2)) # gives 3
For the sake of completeness it is worth to mention two another kinds of approaching counting function calls (see the first version of the answer by user19077881 in the history of edits):
using a function closure
using a function decorator
Notice that if your intention would be to only count calls to a function somehow 'hiding' the fact of counting, the function closure would be probably the best way to go.
METHOD 1:
You can use global variables for them to be accessible everywhere in the code (sometimes can be a bad practice)
Code:
def score_chart():
global num_of_charts
num_of_charts += 1
METHOD 2:
You can use num_of_charts as a function argument and return it at the end of the function (you need to store that value in another variable outside the function)
Code:
def score_chart(num_of_charts):
num_of_charts += 1
return num_of_charts
new_num = score_chart( # put a number here )
After 1st function call you have to pass that new_num as an argument and overwrite it with another value (only if you don't need to go back to previous values)
new_num = score_chart( # put a number here )
new_num = score_chart(new_num)
Also keep in mind that it is += 1 and not =+ 1

Python: How to increment a global variable using a function [duplicate]

This question already has answers here:
Function not changing global variable
(4 answers)
Closed 3 years ago.
counter = 0
def addCounter():
counter = counter + 1
return counter
UnboundLocalError: local variable 'counter' referenced before assignment.
I'm trying to make a counter count every time this function runs. I've tried passing the counter variable in as a parameter as well, but that doesn't work either.
You need:
counter = 0
def addCounter():
global counter
counter = counter + 1
return counter
Explanation: in Python, the declaration of inner variables is implicit, an assignment automatically declares the values on the left-hand side, however that declaration is always in the local scope. That's why if you write this:
counter = 0
def addCounter():
return counter
it will work fine but as soon as you add an assignment
counter = 0
def addCounter():
counter += 1
return counter
it breaks: the assigment adds an implicit local declaration. global overrides this, although it requires that the global exist beforehand, it does not create a global, it just tells the function that this is a global variable it can reassign to.
I've tried passing the counter variable in as a parameter as well, but that doesn't work either.
Indeed not. Python's evaluation strategy is sometimes called "pass by sharing" (or "pass reference by value") which is technically "pass by value" but that term gets a bit confusing as the values in this case are references, the references are copied but the objects referred to are not, and thus the end-behaviour diverges from the normal expectations of "pass by value" expectations.
Using a class rather than global:
Another way to handle (not use) global variables is to wrap the functions and variables you wish to be global in a class.
While this is a little heavy for this specific case - classes add a host of functionality and flexability to the project. (Personally) highly recommended.
For example:
class Processor():
"""Class container for processing stuff."""
_counter = 0
def addcounter(self):
"""Increment the counter."""
# Some code here ...
self._counter += 1
# See the counter incrementing.
proc = Processor()
proc.addcounter()
print(proc._counter)
proc.addcounter()
print(proc._counter)
Output:
1
2

While loop modify global variable

I thought loops in python do not change our global variables; however, the code below gives 10 as a result. Can someone explain what is happening here?
source_col_numbers = 9
i = 1
columns = {}
while i <= source_col_numbers:
columns[i] = list(filter(None , source.sheet1.col_values(i)))
i += 1
print(i)
You have declared i as a global variable and then you are using it in the loop.
So, whatever changes you make to i in your program will be applied on that i since it's a global variable.
Global variable means i has a global scope. If you had created i inside a function, it would have a local scope and could not be accessed outside of the function.
So in your case, changes will be made and output will be 10.
Loops do change global variables, so for each iteration of the loop, i will be incremented by 1.

Global variable functions

I am using a method for storing and recalling global variables in Python. I like it. It seems to work for me. I am not a coder though. I know nothing about this stuff. So, wondering where its limitations will be - how and when I will regret using it in future.
I create a function that will update the value if passed a new one or return the existing value as below:
def global_variable(new_value = None):
# a function that both stores and returns a value
# first deal with a new value if present
if new_value != None
# now limit or manipulate the value if required
# in this case limit to integers from -10 to 10
new_value = min(new_value, 10)
global_variable.value = int(max(new_value, -10))
# now return the currently stored value
try:
# first try and retrieve the stored value
return_value = global_variable.value
except AttributeError:
# and if it read before it is written set to its default
# in this case zero
global_variable.value = 0
return_value = global_variable.value
# either way we have something to return
return return_value
store like this
global_variable(3)
retrieve like this
print(global_variable())
You can just use global variables. If you need to change them within a function you can use the global keyword:
s = 1
def set():
global s
s = 2
print(s)
set()
print(s)
> 1
> 2

Python - using a shared variable in a recursive function

I'm using a recursive function to sort a list in Python, and I want to keep track of the number of sorts/merges as the function continues. However, when I declare/initialize the variable inside the function, it becomes a local variable inside each successive call of the function. If I declare the variable outside the function, the function thinks it doesn't exist (i.e. has no access to it). How can I share this value across different calls of the function?
I tried to use the "global" variable tag inside and outside the function like this:
global invcount ## I tried here, with and without the global tag
def inv_sort (listIn):
global invcount ## and here, with and without the global tag
if (invcount == undefined): ## can't figure this part out
invcount = 0
#do stuff
But I cannot figure out how to check for the undefined status of the global variable and give it a value on the first recursion call (because on all successive recursions it should have a value and be defined).
My first thought was to return the variable out of each call of the function, but I can't figure out how to pass two objects out of the function, and I already have to pass the list out for the recursion sort to work. My second attempt to resolve this issue involved me adding the variable invcount to the list I'm passing as the last element with an identifier, like "i27". Then I could just check for the presence of the identifier (the letter i in this example) in the last element and if present pop() it off at the beginning of the function call and re-add it during the recursion. In practice this is becoming really convoluted and while it may work eventually, I'm wondering if there is a more practical or easier solution.
Is there a way to share a variable without directly passing/returning it?
There's couple of things you can do. Taking your example you should modify it like this:
invcount = 0
def inv_sort (listIn):
global invcount
invcount += 1
# do stuff
But this approach means that you should zero invcount before each call to inv_sort.
So actually its better to return invcount as a part of result. For example using tuples like this:
def inv_sort(listIn):
#somewhere in your code recursive call
recursive_result, recursive_invcount = inv_sort(argument)
# this_call_invcount includes recursive_invcount
return this_call_result, this_call_invcount
There's no such thing as an "undefined" variable in Python, and you don't need one.
Outside the function, set the variable to 0. Inside the loop, use the global keyword, then increment.
invcount = 0
def inv_sort (listIn):
global invcount
... do stuff ...
invcount += 1
An alternative might be using a default argument, e.g.:
def inv_sort(listIn, invcount=0):
...
invcount += 1
...
listIn, invcount = inv_sort(listIn, invcount)
...
return listIn, invcount
The downside of this is that your calls get slightly less neat:
l, _ = inv_sort(l) # i.e. ignore the second returned parameter
But this does mean that invcount automatically gets reset each time the function is called with a single argument (and also provides the opportunity to inject a value of invcount if necessary for testing: assert result, 6 == inv_sort(test, 5)).
Assuming that you don't need to know the count inside the function, I would approach this using a decorator function:
import functools
def count_calls(f):
#functools.wraps(f)
def func(*args):
func.count += 1
return f(*args)
func.count = 0
return func
You can now decorate your recursive function:
#count_calls
def inv_sort(...):
...
And check or reset the count before or after calling it:
inv_sort.count = 0
l = inv_sort(l)
print(inv_sort.count)

Categories