does lack of type declarations make Python unsafe?

Alex Martelli aleax at aleax.it
Tue Jun 17 09:25:46 CEST 2003


Steven Taschuk wrote:

> Quoth Kevin Reid:
>   [...]
>> I'll put my gripe here just because you mentioned named parameters:
>> 
>> I would like to use named parameters more often in Python, but I don't
>> like them being required to be optional.
> 
> They're not, in 2.2.2 at least:
> 
>     >>> def foo(a):
>     ...     print a
>     ...
>     >>> foo(a=3)
>     3
>     >>> foo()
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     TypeError: foo() takes exactly 1 argument (0 given)
> 
> Do I misunderstand your gripe?

Not sure about the OP's gripe, but one mildly legitimate gripe might
be that this simple approach doesn't allow the definer of foo to require
it to be called ONLY as "foo(a=value)" -- the call "foo(value)" (with
an anonymous actual parameter) would also be accepted.  If you want to
force the caller to use a named actual-parameter you'd have to code e.g.:

def foo(**k):
    if k.keys()!=['a']:
        raise TypeError, "foo must be called as foo(a=<somevalue>), only"
    a = k['a']
    """ proceed normally from here onwards """

However, I think the correct answer to this hypothetical gripe is that
Python isn't about "forcing"; it does let you (definer of foo) "force"
your caller to use named-form for the actual parameter, but it's quite
all right that you'll be required to use a couple lines of boilerplate
for the purpose.  Of course, if you did that often, you'd encapsulate the
whole "forcing preamble" as a reusable function such as:

def foo(**k):
    a, b = forcenames(k, ['a', 'b'])
    """ proceed normally from here onwards """

with e.g.

def forcenames(k, names):
    if len(k) != len(names):
        raise TypeError, "named parameters %s are required" % (names,)
    parms = []
    for name in names:
        parms.append(k[name])
    return parms

or some slightly more elaborate version of forcenames to raise better
exceptions if some required name is not among those passed.


Alex





More information about the Python-list mailing list