(Jan-18-2018, 05:20 PM)mepyyeti Wrote: Can you give me a quick run down of the what the function is doing
The function
typed_input()
takes three arguments, it can be used this way
n = typed_input('enter integer: ', int, 'An integer is required, try again...')
It then asks repeatedly a string by printing
enter integer:
, then it tries to convert the string to a python integer by calling
int()
and if it fails, it prints the error message and asks again.
The idea of using
int
and
errmsg
in the parameters is that the function can be used to input other datatypes by using for example
float
or
complex
in the arguments.
The
fuctools.partial()
callable is the python implementation of
partial function application. It takes a function and some arguments and it creates a new callable with fewer arguments, so
partial(type_input, type=int, errmsg='No, try again...')
creates a new callable which takes a single
prompt
argument, the same interface as
input()
This looks a little like meta-programming, because we use a type as a parameter, which is not very frequent. If you look carefully, you'll notice that the only hypothesis on the 'type' parameter is that is is a callable taking one argument and throwing
ValueError
. This can be used to input more general data. For exemple suppose I want the user to enter a probability, which is a real number between 0 and 1, I can write
def probability(arg):
p = float(arg)
if not (0.0 <= p <= 1.0):
raise ValueError(('Invalid value for probability():', arg))
return p
proba_input = partial(typed_input, type=probability,
errmsg='A probability is required, try again...')
qux = proba_input("Give me a probability > ")
This will prompt the user until she enters a number between 0 and 1 !