(Jan-18-2018, 06:20 PM)Gribouillis Wrote:(Jan-18-2018, 05:20 PM)mepyyeti Wrote: Can you give me a quick run down of the what the function is doing
The functiontyped_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 printingenter integer:
, then it tries to convert the string to a python integer by callingint()
and if it fails, it prints the error message and asks again.
The idea of usingint
anderrmsg
in the parameters is that the function can be used to input other datatypes by using for examplefloat
orcomplex
in the arguments.
Thefuctools.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, sopartial(type_input, type=int, errmsg='No, try again...')
creates a new callable which takes a singleprompt
argument, the same interface asinput()
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 throwingValueError
. 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 !
Working on partials, I'm noticing that the variable qux isn't really necessary. Suppose: the user is ask to input probability 3 times.
why wouldn't I just use
proba_input = partial(typed_input, type=probability, errmsg='prob reqd')?
I mean at its extreme end I could just reuse the same variable and just overwrite the value. I'm not quite clear on the benefit of
foo = bar(original_func_as_place_holder,para1='a',para2='b')when I have already set up
bar = partial(original_func_as_place_holder,para1='a',para2='b').
I mean since foo is a variable I can't just use it as a function every time I ask for probability input. I have to rewrite the partial anyway.