current position:Home>Python code reading (Chapter 61): delaying function calls

Python code reading (Chapter 61): delaying function calls

2022-02-01 07:47:55 FelixZ

Python Code reading collection Introduction : Why not recommend Python Beginners directly look at the project source code

The code read in this article is implemented after a given delay time , Call the function of the specified function .

The code snippet read in this article comes from 30-seconds-of-python.

delay

from time import sleep

def delay(fn, ms, *args):
  sleep(ms / 1000)
  return fn(*args)

# EXAMPLES
delay(
  lambda x: print(x),
  1000,
  'later'
) # prints 'later' after one second
 Copy code 

delay Function receives a specified function fn, One delay time ms And specify the parameters of the function *args, After a specified delay , Returns the specified function fn Is the result of the call .

Function USES sleep() Method to delay , Then the specified function is called. .delay When the function is called , have access to lambda Anonymous function of expression , You can also use general functions . The thing to notice is when fn An exception occurs when a keyword parameter exists .

>>> from time import sleep
>>>
>>> def delay(fn, ms, *args):
...   sleep(ms / 1000)
...   return fn(*args)
...
>>> def f(pos_only, /, standard, *, kwd_only):
...     print('pos_only:{}\nstandard:{}\nkwd_only:{}'.format(pos_only,standard,kwd_only))
...
>>> delay(f, 1000, 1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in delay
TypeError: f() takes 2 positional arguments but 3 were given
>>> delay(f, 1000, 1, 2, kwd_only = 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: delay() got an unexpected keyword argument 'kwd_only'
 Copy code 

copyright notice
author[FelixZ],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010747544565.html

Random recommended