Python Forum

Full Version: Random Python Feature
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm working on an interface where the user selects functions. But some of those functions are meta-functions that create the function you want. But the meta-functions can have different types of parameters. How do I validate them? The parameter names are pretty consistent, so I can base the validation off the parameter names. But how do I get the parameter names?

Now, because of the way I write my docstrings, I could write something to parse func.__doc__ and return the parameter names. But is there a way to get that information straight from the function object? It turns out there is:

func.__code__.co_varnames[:func.__code__.co_argcount]
I love Python.
There also inspect module that is a little more robust,as it will give all info also about default arguments and keyword arguments.
def foo(arg, new='snake', **kwargs):
    return f'python-forum {arg} a {new}? no {kwargs}'
Test:
>>> import inspect
>>> 
>>> foo.__code__.co_varnames[:foo.__code__.co_argcount]
('arg', 'new')
>>> 
>>> inspect.signature(foo)
<Signature (arg, new='snake', **kwargs)>
>>> 
>>> foo('io', python='forum')
"python-forum io a snake? no {'python': 'forum'}"