Random Python Feature - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: Random Python Feature (/thread-20682.html) |
Random Python Feature - ichabod801 - Aug-25-2019 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. RE: Random Python Feature - snippsat - Aug-25-2019 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'}" |