Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an argument to a global variable with the same name

How can I assign a function argument to a global variable with the exact same name?

Note: I can't do self.myVariable = myVariable because my function is not inside of a class.

When write the following code, I get an error saying that "argument is both local and global."

myVar = 1
def myFunction(myVar):
    global myVar

Is this impossible? and if so is it uncommon in other languages? Coming from java I'm used to this.myVar = myVar

Edit I already know that I can rename the variable. That's the easy way out.

like image 836
Stephan Avatar asked Jul 11 '13 19:07

Stephan


1 Answers

Best solution: refactor your code. Rename something, or use an object with object properties instead of a global variable.

Alternative, hacky solution: modify the global variable dict directly:

my_var = 1
def my_function(my_var):
    globals()['my_var'] = my_var
like image 110
user2357112 supports Monica Avatar answered Sep 28 '22 05:09

user2357112 supports Monica