-2

lots of built-in python functions do this but I can't figure out how to create one on my own. I want something like this

def FCTN(Variable)
    Variable = Variable + 5
    

a=5 # define global variable
FCTN(a) # call fctn on global variable

when I do print(a) its value is still 5 of course, but I want the above fctn to change its value to 10, i.e. sustainably modify its input

the 2 routines I found are based on making changes to the dictionary containing the current scope’s global variables, sitting behind the global() fctn, i.e.


a=5
def fctn(Variable):
    globals()[Variable] += 5

fctn('a') 

the function needs to be called including the keyword 'a' rather than the variable a which is rather unsatisfying

the other routine modifies the global dictionary within the alpha fctn


a=5
fctn= lambda: globals().update(a=a+5)

fctn(a) 

which does change the value of 'a' but in a slightly different manner as in my example in the beginnig...

so my question is: what do I need to add to my example function above so that the value of a gets permanently changed?

Lippis
  • 1
  • 1
  • *”lots of built-in python functions do this”* — Can you name a few…? – deceze Aug 06 '23 at 18:08
  • No built in functions do this. For starters, mutable glopbal state is a bad practice. Furthermore, you seem to actually want *call by reference semantics*, which python never supports. Which is a good thing. – juanpa.arrivillaga Aug 06 '23 at 18:41
  • "i.e. sustainably modify its input". It's input is an `int` object, which is immutable. The input is *not a variable*. – juanpa.arrivillaga Aug 06 '23 at 18:42
  • You could conceivably call your function as `FCTN(5)`. What then? There's no "global variable" here which could be modified. Even with `FCTN(a)`, it would be **extremely surprising behaviour** if `a` would change (as long as we're talking about integer values). Simply no builtin function does that, and it's basically impossible to write any such function. – deceze Aug 07 '23 at 12:44

0 Answers0