News How To Create and Use Python Functions

Status
Not open for further replies.
Not 100% the same, but much terser while not overly dense: 🙂

Python:
from operator import call
from psutil import cpu_count, cpu_freq, cpu_percent, virtual_memory

funcs = {
    'cpuspeed': lambda: f"The CPU speed is {cpu_freq([1])[0][0]:,} MHz.",
    'cores':    lambda: f"This CPU has {cpu_count(False):,} cores and {cpu_count():,} threads.",
    'cpu':      lambda: f"Current CPU usage is {cpu_percent():,}%.",
    'ram':      lambda: f"There is {round(virtual_memory()[1] / 1024 ** 2):,} MB of available RAM."
}
combined_funcs = lambda: '\n'.join(call(func) for func in funcs.values())
try:
    while True:
        func_to_call = funcs.get(input("Please type 'cpu', 'ram', 'cores', 'cpuspeed' or press ENTER to show all stats: "), combined_funcs)
        print(call(func_to_call))
except KeyboardInterrupt:
    print("Exiting…")
 
  • Like
Reactions: bit_user
Another Python article; more missed opportunities. This time:
  • storing & passing functions as variables & parameters
  • lamdas (as @Li Ken-un demonstrated)
  • packed argument lists
  • higher-order functions: filter(), map()
  • member functions & static member functions (though, I don't know if you've yet introduced objects)
  • curring (i.e. function argument binding)

Here's a simple example demonstrating several of those techniques:
Python:
add = lambda x, y: x + y
print( "add( 7, 9 ) =", add( 7, 9 ), "\n" )

def curry_first( f, first ):
    return lambda *args: f( first, *args )

add_1 = curry_first( add, 1 )
for i in map( add_1, [ 1, 2, 3 ] ):
    print( i )

Output:
Code:
add( 7, 9 ) = 16

2
3
4

Explanation:
  • lambda is used to define an unnamed function. In this case, a lambda with 2 arguments is defined which simply adds them.
  • The variable add is defined to hold this lambda, which effectively turns it into a function.
  • To demonstrate this, it's used to add 7 and 9.
  • Next, the curry_first() function is used to bind a value of 1, for the first argument of add. The resulting function takes only a single argument and adds 1 to it.
  • Now, we use the map() builtin function to apply add_1() to each element in the list [ 1, 2, 3 ].
  • This is done in a for loop, so the resulting value can be printed. I could've used a list comprehension to print the result in one shot, but I figure the example is already terse enough.
 
Last edited:
  • Like
Reactions: Li Ken-un
Python:
def curry_first( f, first ):
    return lambda *args: f( first, *args )
curry_first is just partial from functools. 😉

Python:
from operator import add
from functools import partial

add_1 = partial(add, 1)

print(f"add( 7, 9 ) = {add( 7, 9 )}\n" )
for i in map(add_1, [1, 2, 3]):
    print(i)
Python:
from operator import add
from functools import partial
from toolz import compose

add_1 = partial(add, 1)

print(f"add( 7, 9 ) = {add( 7, 9 )}\n" )

add_1_and_print = compose(print, add_1)

for i in [1, 2, 3]:
    add_1_and_print(i)

There are some additional imports that go very well with the stuff in functools, including itertools and operators. I recommend toolz which provides even more constructs like compose and pipe without having to define them yourself in every project/script.
 
Last edited:
  • Like
Reactions: bit_user
Status
Not open for further replies.