Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #10811 > unrolled thread
| Started by | Lee Harr <missive@hotmail.com> |
|---|---|
| First post | 2011-08-03 20:32 +0430 |
| Last post | 2011-08-03 20:32 +0430 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
parsing function parameters Lee Harr <missive@hotmail.com> - 2011-08-03 20:32 +0430
| From | Lee Harr <missive@hotmail.com> |
|---|---|
| Date | 2011-08-03 20:32 +0430 |
| Subject | parsing function parameters |
| Message-ID | <mailman.1843.1312387394.1164.python-list@python.org> |
I am trying to get some information about a function
before (and without) calling it.
Here is what I have so far. I chose to go with a
regular expression, so now I have 2 problems :o)
def pdict(f, pstr):
'''given a function object and a string with the function parameters,
return a dictionary of {parameter name: default value or None, ...}
I don't really need the actual default values, just knowing that
they exist or having their string representations would be fine.
def foo(x, y, z=50):
pass
ps = 'x, y, z=50'
pdict(foo, ps)
{'x': None, 'y': None, 'z': 50}
OR: {'x': '', 'y': '', 'z': '50'}
OR: {'x': False, 'y': False, 'z': True}
Note that the parameter list can be arbitrarily complex
(as long as it is legal python)
def bar(m, n=(1, 2, 3), o = ('n=5', 'or anything legal')):
pass
pps = 'm, n=(1, 2, 3), o = ('n=5', 'or anything legal')'
pdict(bar, pps)
{'m': None, 'n': '(1, 2, 3)', 'o': "('n=5', 'or anything legal')"}
'''
prs = f.func_code.co_varnames
rxl = [r'(\s*%s\s*=(?=(?:\s*\S+))\s*\S+)\s*'%pr for pr in prs]
rx = ','.join(rxl)
print rx
import re
re.match(rx, pstr).groups()
This regex works in limited situations, namely when every parameter
has a default value, but I can't figure out how to also make it
match a parameter that has no default.
I am open to any solution, though I am reluctant to pull in any more
external libraries just for this one little enhancement. I have it
working by just splitting the pstr on comma, except of course that
it fails when the default value contains a comma (a tuple or list,
for instance).
Any assistance or ideas appreciated.
Back to top | Article view | comp.lang.python
csiph-web