Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random Python Feature
#1
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#2
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'}"
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  a feature i would like to see added to Python Skaperen 0 505 Oct-30-2023, 12:30 AM
Last Post: Skaperen
  Can the video calling feature be used from python telegram bot api? Kumarkv 0 1,823 May-30-2020, 01:34 PM
Last Post: Kumarkv
  Python in Feature film Larz60+ 0 3,137 Dec-11-2016, 02:17 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020