Home > Blockchain >  Create an alias to a function with a parameter
Create an alias to a function with a parameter

Time:07-03

The pprint function includes a parameter sort_dicts=True which doesn’t suit me.

I know that something like:

from pprint import pprint
thing = pprint

will effectively create an alias to the pprint function.

How do I define a function which acts as an alias to the pprint function with sort_dicts=False ? Something like this:

#   I know this is wrong
newpp = pprint(…, sort_dicts=False)

CodePudding user response:

You're looking for partial application of a function. In Python, there is a standard library function called functools.partial that will do it for you.

from functools import partial

newpp = partial(pprint, sort_dicts=False)

You can do this by hand in Python, too. If you're interested in seeing the mechanism behind it, you can check out the link above, which has an example implementation.

Note that, with partial, somebody can still explicitly override your keyword arguments. If I call newpp(x, sort_dicts=True), then my sort_dicts wins over yours. But if the caller is cooperative and doesn't supply the keyword argument, then yours gets taken.

CodePudding user response:

I have accept Silvio’s answer, which refers to https://docs.python.org/3/library/functools.html#functools.partial. In turn, that reference includes a manual way of doing this, though it’s a way of emulating the partial() function more generally.

In answer to my original question, I have ended up with the following:

import pprint
def pq(*fargs, **fkeywords):
    keywords = { 'sort_dicts': False }
    newkeywords = {**keywords, **fkeywords}
    return pprint.pprint(*fargs, **newkeywords)

elements = {
    'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium',
    'Be': 'Beryllium', 'B': 'Boron', 'C': 'Carbon',
    'N': 'Nitrogen', 'O': 'Oxygen', 'F': 'Flourine', 'Ne': 'Neon'
}

pprint.pprint(elements) #   sorted
pq(elements)            #   unsorted

Of course the question was how to do this in generally, but it’s even simpler once you get your head around the arguments.

  • Related