By Hungpham3112 via Discussions on Python.org at 18Apr2022 08:54:
I’m still new with functional programming in Python.
“Functional programming” and “pure functions” are not identical
concepts, though you need pure functions to do functional programming.
A pure function does not change any external state: everything it knows
comes from its arguments, and the only results come from the return
statement. And it does not change the state of anything visible outside.
I got a snippet:
def format_data(data: str) -> list[str]:
formatted_data = data.strip().split(",")
return formatted_data
def format_data(data: str) -> list[str]:
return data.strip().split(",")
These are both pure functions.
Which one is considered as pure function and why? After that, how I can use formated_data
for following snippet to make it pure function. Thanks.
def is_length_valid(data: str) -> bool:
return len(format_data(data)) == 26
This is also a pure function.
Here is a nonpure function (example, untested):
x = 1
def up_x(y):
global x
x += y
print(x)
up_x(2)
print(x)
This code should print 1 and then 3. The external variable x
has been
changed, so the up_x
function has side effects.
Here is a less obvious nonpure function:
nums = [2, 1, 3]
def sort(ary):
ary[:] = sorted(ary)
print(nums)
sort(nums)
print(nums)
should print [2, 1, 3]
and then [1, 2, 3]
. The nums
list has been
changed. This is because all Python variables are references, so the
variable ary
inside the function refers to the same list that nums
refers outside.
Here is a pure function:
nums = [2, 1, 3]
def sort(ary):
return sorted(ary)
print(nums)
nums2 = sort(nums)
print(nums)
print(nums2)
which sould print [2, 1, 3]
and then [2, 1, 3]
and then [1, 2, 3]
.
Even though the variable ary
inside the function refers to the same
list as nums
outside, it does not modify the array in place. Instead
it computes a new list containing the elements of ary
sorted. And
returns the new list. So we see that nums
is unchanged after the
function call and nums2
refers to the new list.
Rules of thumb:
- no modification global variables or other variables from outer scopes
- no modification of the internal parts of values you receive; instead
make new structures or values containing the results of your function
Cheers,
Cameron Simpson cs@cskk.id.au