[Python-ideas] Keyword only argument on function call

Jonathan Fine jfine2358 at gmail.com
Thu Sep 6 15:10:49 EDT 2018


Summary: I addressed the DEFINING problem. My mistake. Some rough
ideas for the CALLING problem.

Anders has kindly pointed out to me, off-list, that I solved the wrong
problem. His problem is CALLING the function fn, not DEFINING fn.
Thank you very much for this, Anders.

For calling, we can use https://docs.python.org/3/library/functions.html#locals

      >>> lcls = locals()

      >>> a = 'apple'
      >>> b = 'banana'
      >>> c = 'cherry'

      >>> dict((k, lcls[k]) for k in ('a', 'b', 'c'))
      {'b': 'banana', 'c': 'cherry', 'a': 'apple'}

So in his example

       foo(a=a, b=b, c=c, d=3, e=e)

one could instead write

      foo(d=3, **helper(locals(), ('a', 'b', 'c', 'e')))

or perhaps better

    helper(locals(), 'a', 'b', 'c', 'e')(foo, d=3)

where the helper() picks out items from the locals(). And in the
second form, does the right thing with them.

Finally, one might be able to use

      >>> def fn(*, a, b, c, d, e): f, g, h = 3, 4, 5
      >>> fn.__code__.co_kwonlyargcount
      5
      >>> fn.__code__.co_varnames
      ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
      >>> fn.__code__.co_argcount
     0

to identify the names of all keyword arguments of the function foo(),
and they provide the values in locals() as the defaults. Of course,
this is somewhat magical, and requires strict conformance to
conventions. So might not be a good idea.

The syntax could then be

    localmagic(foo, locals())(d=3)

which, for magicians, might be easier. But rightly in my opinion,
Python is reluctant to use magic.

On the other hand, for a strictly controlled Domain Specific Language,
it might, just might, be useful. And this list is for "speculative
language ideas" (see
https://mail.python.org/mailman/listinfo/python-ideas).

-- 
Jonathan


More information about the Python-ideas mailing list