The answer equals the definition of side effects
.
Up to now, I don't find out a precise answer. The python doc says:
Functional style discourages functions with side effects that modify internal state or make other changes that aren’t visible in the function’s return value.
What is modify internal state
and make other changes that aren’t visible...
?
Is binding varibles to objects(just binding, not modifying) means no side effects? e.g.a=1
or a=[1,2,3]
or a,b=1,2
.
Here are 4 functions. Are they all with no side effects? why?
Note, assuming the argument n
must be an int
object.
def purefunc1(n):
def getn(n):
return [1,2,3,4,5][:n-1],[1,2,3,4,5][:n]
def addn(fir,sec,thd):
return fir+sec+thd
return addn(getn(n)[0],['HEY'],getn(n)[1])
def purefunc2(n):
def getn(n):
#bind
arr=[1,2,3,4,5]
return arr[:n-1],arr[:n]
def addn(fir=[],sec=[],thd=[]):
return fir+sec+thd
#bind
arg1,arg3=getn(n)
return addn(arg1,['HEY'],arg3)
def purefunc3(n):
arr=[1,2,3,4,5]
def getn(n):
#closure 'arr'
return arr[:n-1],arr[:n]
def addn(fir=[],sec=[],thd=[]):
return fir+sec+thd
#bind
arg1,arg3=getn(n)
return addn(arg1,['HEY'],arg3)
def purefunc4(n):
def arr():
return [1,2,3,4,5]
def getn(n):
#closure
return arr()[:n-1],arr()[:n]
def addn(fir=[],sec=[],thd=[]):
return fir+sec+thd
#bind
arg1,arg3=getn(n)
return addn(arg1,['HEY'],arg3)
print (purefunc1(3))
print (purefunc2(3))
print (purefunc3(3))
print (purefunc4(3))
My guess:purefunc1
is with no side effects.But I don't know the following purefunc*.
the output is:
[1, 2, 'HEY', 1, 2, 3]
[1, 2, 'HEY', 1, 2, 3]
[1, 2, 'HEY', 1, 2, 3]
[1, 2, 'HEY', 1, 2, 3]
If you ask why exists such odd functions, the answer is it's just for convenience. The real function is complicated. but if you are interested, you can click here to see whether the function ieval
is with no side effects or not.
Thank you all guys in advance.