What use is of this 'cast=float ,'?

Rick Johnson rantingrickjohnson at gmail.com
Sat Oct 28 13:47:49 EDT 2017


On Friday, October 27, 2017 at 3:35:45 PM UTC-5, Robert wrote:
> I read below code snippet on line. I am interested in the
> second of the last line: `cast=float`. I've tried it in
> Python. Even simply with: `float` It has no error, but what
> use is it? 
> 
> self.freqslider=forms.slider(
>      parent=self.GetWin( ),
>      sizer=freqsizer,
>      value=self.freq,
>      callback= self.setfreq,
>      minimum=−samprate/2,
>      maximum=samprate/2,
>      num_steps=100,
>      style=wx.SL_HORIZONTAL,
>      cast=float ,
>      proportion=1,
> )

This is a fine example of the distinctly pungent form of
code-smell otherwise known as: "unintuitive naming
convention".

A more informative keyword argument would have been
something like "castFunc" or "castTo" or even "returnType",
any of which would indicate that the argument is (depending
on the specific implementation of course) expected to be a
function object or that some specific type of "casting
action" is to be performed on the return value. Whereas,
using the ambiguous word "cast" leaves too much to the
imagination. And while my crazy-uncle-who-lives-in-the-
basement swears that lingerie magazines are better than the
nudie mags (because, in the case of the former, more is
reserved for the imagination), an API that requires
imagination to grokk is a poorly designed API.

Here is an interactive example of assigning a builtin to a
generic, allbeit very _intuitive_, symbol.

    >>> value = "12.3"
    >>> type(value)
    <type 'str'>
    >>> castFunc = float
    >>> valueAsFloat = castFunc(value)
    >>> valueAsFloat
    12.3
    >>> type(valueAsFloat)
    <type 'float'>
    >>> value = "12.3"
    #
    # And now for integers...
    #
    >>> castfunc = int
    >>> valueAsInteger = castfunc(value)
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        valueAsInteger = castfunc(value)
    ValueError: invalid literal for int() with base 10: '12.3'

Oops! O:-) Well, don't blame me because Python is so hobbled that
it cannot even convert a string-ified version of a float into
an integer. *SHRUGS*




More information about the Python-list mailing list