0
How to update int value inside python function
Hi I know I can return from function. But what I need is a c++ mechanism of call by reference in python . In other words, I have a python function which takes int and update it's value. How to get this updated value out of function? Attached code should print 11 for second time (I.e. after function call) I am aware about immutable int and need some elegant solution to have updated value of int. https://sololearn.com/compiler-playground/c1vy8009BnQX/?ref=app
22 Antworten
+ 3
Pass parameters by reference:
https://sololearn.com/compiler-playground/cFKsDSDxhyBG/?ref=app
+ 4
class IntegerHolder:
def __init__(self, initial_value):
self.value = initial_value
def update_value(holder):
holder.value += 10 # Increment the value by 10
# Usage
value_holder = IntegerHolder(5)
update_value(value_holder)
print(value_holder.value) # Output will be 15
+ 3
The C++ mechanism of call by reference doesn't exist in Python, but if we should look at an elegant solution as you prefer, then you could use a class with an attribute that updates.
+ 3
if you're going the ctype route, then maybe this can get you started...
https://stephenscotttucker.medium.com/interfacing-JUMP_LINK__&&__python__&&__JUMP_LINK-with-c-using-ctypes-classes-and-arrays-42534d562ce7
https://www.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://www.youtube.com/watch%3Fv%3DneexS0HK9TY&ved=2ahUKEwjqw-qPi5iKAxUobfUHHbPlGxcQo7QBegQIDRAF&usg=AOvVaw2MZhPOnnvnYVeBk-QMApBW
+ 2
> this was already mentioned:
we can use mutable objects (like a list that contains the object that should be modified in the function)
> this was already mentioned:
we can also use the return statement inside the function and update the variable a in the main scope.
> we could also use the `global` keyword , to make the variable `a` of the main scope accessible from the function.
it works, but this is not seen as a good practice.
def getNewValue_1():
global a
a = a + 1
a = 10
print(a)
getNewValue_1()
print(a)
+ 2
Aha, interesting example, Vitaly Sokol so call by reference in Python actually exist, but only with that ctypes library, I assume......
+ 2
Jan
yes, directly using dict is simpler. Simplenamespace just makes getting a dictionary's value a little prettier.
player.points # class or Simplenamespace
player["points"] # dictionary
player[0] # list
Ultimately, they're all encapsulated mutable data.
+ 1
When you pass the variable a to the function, it takes a reference of a. This means changes made with that a will be done only with that copy and won't affect the value of the original a
You can do this to change the value:
a = 10
print(a)
a = getNewValue(a)
print(a)
This will assign the value of a in the function to the original a
Or you can also use an list, but I doubt it'll be useful for your case
+ 1
it's a bit ugly, but lists are mutable and passed by reference
not recommended and not elegant, but maybe:
def getNewValue(a):
a[0] += 1
a = [10]
print(a[0])
getNewValue(a)
print(a[0])
generally, if you want mutations in Python, do it with list.
Or just reassign, as Afnan Irtesum Chowdhury suggested. It's Python not C or C++...
+ 1
You need to do it this way.......
def getNewValue(a):
a = a + 1
return a
a = 10
print(a)
a = getNewValue(a)
print(a)
In this case, it first prints 10, and then the a variable gets overwritten by the function and changes to 11.
+ 1
Perfect Vitaly Sokol
+ 1
It's a roundtrip, though, so the conversions might conceivably add some overhead.
+ 1
Bob_Li The question is whether it actually increases speed and performance, or is the library more suitable for loading external native dlls, since normal pointer use in C sometimes decrease the speed.
+ 1
yes, just using C is not a guarantee for speedup. The complexity of the calculations required will determine the effectiveness of an external library.
+ 1
JaScript
Maybe SimpleNamespace is simpler than initialising a class just for the dot notation.
# enable dot notation for dict
from types import SimpleNamespace
a = SimpleNamespace(**{'v':0})
print(a.v) # 0
b = SimpleNamespace(**{'v':0})
print(b.v) # 0
# change initial value
a.v = 10
b.v = 42
# mutating function
def update_value(n):
n.v += 1
# call update_value on a
update_value(a) # 10
print(a.v) # 11
# call update_value on b
update_value(b) #42
print(b.v) #43
# use a.v and b.v as int
a.v += 60
b.v = a.v*2
print(a.v) # 71
print(b.v) # 142
+ 1
Bob_Li I have a simpler solution with a dictionary......
player = {
"points" : 10
}
def getNewValue():
player["points"] += 1
print(player["points"])
getNewValue()
print(player["points"])
0
Thanks Afnan Irtesum Chowdhury and Bob_Li
0
You can use direct meathod of 'int' or indirect. Such as using print, we can use direct meathod of int.
0
Thanks Jan sounds good 👍