Don't know where I read this recommendation, but if I need to pass sequence of values as function arguments, I'm using tuple. Probably I'm doing it because it immutable and I was recommended to do so by reading some book or passing course. But now I need a function where list should be passed as argument (because I need to use pop inside of it). And now when I'm little more experienced then before, I just wondering, are there any problems in passing list as function argument?
I know that using a list as default value - isn't a good thing. But what about simple argument? Are there any problems that can happen after it, or the only rule that I should follow - do not use list as argument default value?
For example, doing something like this - isn't a good thing:
def hello(arg_string="abc", arg_list = []):
print arg_string, arg_list
arg_string = arg_string + "defg"
arg_list.append("A")
for i in range(4):
hello()
Output would be
abc []
abc ['A']
abc ['A', 'A']
abc ['A', 'A', 'A']
But what if I want something simple, with or without changing the object but where can I be sure that I could document that I changed something:
def hello(arg_list = []):
for i in arg_list:
print(i)
hello(["1","2","3"])
Output here would be:
1
2
3
If you pass a mutable object to a function the function can change the contents:
Normally functions should indicate if they alter the input or not, so this might only be an issue when the function has no or only poor documentation.
However you can always pass in a copy or do the copy in the function if you change the input:
As a rule of thumb (there are exceptions) a function should only modify the input if it doesn't return anything - or should leave the input alone if it does return something.