Let's say we have a function foo()
def foo():
foo.a = 2
foo.a = 1
foo()
>> foo.a
>> 2
Is this pythonic or should I wrap the variable in mutable objects such as a list?
Eg:
a = [1]
def foo(a):
a[0] = 2
foo()
>> a
>> 2
Let's say we have a function foo()
def foo():
foo.a = 2
foo.a = 1
foo()
>> foo.a
>> 2
Is this pythonic or should I wrap the variable in mutable objects such as a list?
Eg:
a = [1]
def foo(a):
a[0] = 2
foo()
>> a
>> 2
Since you "want to mutate the variable so that the changes are effected in global scope as well" use the global
keyword to tell your function that the name a
is a global variable. This means that any assignment to a
inside of your function affects the global scope. Without the global
declaration assignment to a
in your function would create a new local variable.
>>> a = 0
>>> def foo():
... global a
... a = 1
...
>>> foo()
>>> a
1
Use a class (maybe a bit overkill):
class Foo:
def __init__(self):
self.a = 0
def bar(f):
f.a = 2
foo = Foo()
foo.a = 1
bar(foo)
print(foo.a)