This question is related to my earlier question here: python update outer passed value from within a for loop.
Coming from a Perl background it has never been a problem to pass a variable by reference and update the value from within a child scope as in the for-loop example below:
#!/usr/bin/perl
my ($str1,$str2) = ('before','before');
print "before - str1:'$str1', str2:'$str2'\n";
foreach my $str($str1,$str2){$str = 'after'}
print "after - str1:'$str1', str2:'$str2'\n";
I understand in Python this is not possible as variables are imported by-value rather than by-reference, the only solution I've found within Python so far which achieves exactly what I need is:
def changeValue(str):
return 'after'
str1 = 'before'
str2 = 'before'
for s in str1,str2: print s
str1 = changeValue(str1)
str2 = changeValue(str2)
for s in str1,str2: print s
Although not ideal this would be OK if I could make the function 'changeValue' calls from within a for-loop - rather than calling them individually as above - but then I am back to the original "can't pass a variable by reference" problem.
I am sure that there must be a simple and less convoluted Pythonic way to achieve what I'm after?