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
foo.a
means where foo
is a function name. How does the example 1 (as mentioned in the question) work like a mutable variable?foo.a = 2
). This is a legal but not common practice (but not totally uncommon). If you need to pair behavior with state what you want is to declare a class.a
is no attribute in your example, this may be misleading.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)
self.a = 0
in Foo.__init__
?
function_name.a
(Eg 1) means and why does it simulate mutable object?global
keywords).