Tuesday, 19 September 2017

Python: Reassign value to variable (using a function)











How can I reassign a value to a variable that is passed as a function argument?



For instance, what I am looking to do is:



foo = True

def convert(foo):
if foo == True:
foo = 'on'

elif foo == False:
foo = 'off'
return foo


where foo is now a string. The problem with the method above is that in order to change foo from a boolean type to a string type the following must be passed:



foo = convert(foo)



whereas I am looking to do something like:



convert(foo)


or,



foo.convert()



Any ideas?


Answer



foo = convert(foo)


is the cleanest and most explicit way to achive this. This is the way most people would recommend, if you are sure you even need to reassign a string to a bool variable.



foo.convert()



is something you can do on an instance of a class that you need to define. You can do it, but it's not worth the hassle. Just reassign the variable, that's it.



convert(foo) # actually, just convert()


can also work, but you'd have to use the global keyword in the convert function. This is not recommended, especially when it's so easy to avoid.



In [1]: foo = True

In [2]: def convert():

...: global foo
...: foo = 'on' if foo else 'off'
...:

In [3]: convert()

In [4]: foo
Out[4]: 'on'

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...