Monday, April 11, 2005

how well do you know python, part 3

Here's one to file in the "cryptic documentation" category.
>>> import inspect
>>> help(inspect.getargspec)
Help on function getargspec in module inspect:

    Get the names and default values of a function's arguments.
    A tuple of four things is returned: (args, varargs, varkw, defaults).
    'args' is a list of the argument names (it may contain nested lists).
    'varargs' and 'varkw' are the names of the * and ** arguments or None.
    'defaults' is an n-tuple of the default values of the last n arguments.
What conditions would you guess might cause getargspec's args list to contain nested lists?


Xentac said...

If the arg list contains a tuple:
>>> import inspect
>>> def a((b,c,d),e):
... pass
>>> inspect.getargspec(a)
([['b', 'c', 'd'], 'e'], None, None, None)

Why you'd want to refer to a function's arg's tuple elements directly, I'm not quite sure... maybe if you wanted to force a certain number of elements in the tuple.

Heck, I didn't even know you could do that.

Anonymous said...

That's pretty neat -- and begging for some abuse ;)

James Harlow said...

I find it mainly useful for documenting function structure:

def parse_email(email_tuple):

def parse_email((header, body)):

The main gain here is not so much in documenting how many elements an email_tuple has, but what order they come in - this is particularly useful if you're the kind of programmer (like I am) who throws around a lot of tuples.