Fredrik Håård's Blaag

@fhaard
I'm a programmer, consultant, developer, occasional teacher and speaker. Among my least disliked programming languages are Python, and a majority of these posts are related to Python in one way or another.
RSS Feed

Sending non-valid names as arguments

I got a feature request on hgapi the other day, pointing out that it was not possible to filter the Mercurial log using the API, since there is no dedicated way to do it and the fallback method - sending keyword arguments that will be passed to the command line - does not work. The signature of the method in question is

def hg_log(self, identifier=None, limit=None,
           template=None, branch=None, **kwargs):

with kwargs accepting any keyword arguments and passing them to the command line. So, for getting a log by branch, trying

repo.hg_log(-b=mybranch)

seems like a good idea, until you realize that '-b' is not a valid identifier, and so this code is invalid. However, almost all Mercurial options you might want to send like this starts with a dash, so what is the point of using kwargs at all?

Notice: Entering bad practice land!

It is totally possible to send keyword arguments to a function in Python that are not valid identifiers, by using argument unpacking. Given a function like this:

>>> def myfunc(positional, kwarg='Hello', **kwargs):
>>>     print(positional)
>>>     print(kwarg)
>>>     for key in kwargs:
>>>         print("%s: %s" % (key, kwargs[key]))

you can send any dict in like this:

>>> myfunc(1, **{'-1-': 'dash-one-dash'})
1
Hello
-1-: dash-one-dash

Not a very nice way of doing things, but can be handy in - for example - a fallback case where you, want to support future arguments, obscure arguments, and generally just anything.

(hgapi 1.3.1a3 was just uploaded to the cheeseshop; hg_log now takes a 'branch' argument)
Blaag created 121102 17:29
blog comments powered by Disqus


Page created using blaag and abusing docutils. RSS Feed generated using PyRSS2Gen.