[Python-ideas] Improving fn(arg=arg, name=name, wibble=wibble) code

Jonathan Fine jfine2358 at gmail.com
Thu Sep 13 03:21:18 EDT 2018


Summary: Michael Selik has produced a nice refactoring of an example.
I suggest further refactoring, to create a function decorator that
does the job. This might be useful if the example is an instance of a
common use pattern.

Michael Selik wrote

>     def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,
>              closefd=True, opener=None, *, loop=None, executor=None):
>         return AiofilesContextManager(_open(**locals()))

> I normally dislike the use of **locals(), but here it helps make explicit
> that the "public" open function passes all arguments through to its helper.

Here's the call signature for the built-in open

    >>> help(open)
    open(file, mode='r', buffering=-1, encoding=None,
         errors=None, newline=None, closefd=True, opener=None)

And for the new open

    Same as builtin open, with (keyword-only)  loop=None, executor=None added.


To explore, let's refactor, as if this were a common use pattern. Your
code, Michael, (almost) reduces the definition of the new open
function to

    A signature
    A function to call on the resulting locals()

So how would we refactor this. I suggest (not tested)

    @wibble(sig)
    def new_open(kwargs):
        return AiofilesContextManager(_open(**kwargs))

The sig argument to the decorator wibble could be an instance of

    https://docs.python.org/3/library/inspect.html#inspect.Signature

The semantics of wibble should be such that the above is equivalent to
Michael's code, quoted at the top of this post.

Finally, we'd like some easy way of combining the signature of (the
built-in) open with the additional loop and executor parameters.

I see two questions arising. First, can this conveniently implemented
using Python as it is? Second, does the decorator wibble (perhaps
enhanced) help with common use patterns.

I'm grateful to you, Michael, for your nice clear example of
refactoring. Given the narrow context of the problem, I don't see how
it could be bettered. But if it's a common use pattern, refactoring
into a decorator might be good.

Would anyone here like to try coding up a proof-of-concept decorator?
Or explore code-bases for this and similar use patterns? I'm busy to
the end of this month, so have little time myself.

-- 
Jonathan


More information about the Python-ideas mailing list