Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10811 > unrolled thread

parsing function parameters

Started byLee Harr <missive@hotmail.com>
First post2011-08-03 20:32 +0430
Last post2011-08-03 20:32 +0430
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  parsing function parameters Lee Harr <missive@hotmail.com> - 2011-08-03 20:32 +0430

#10811 — parsing function parameters

FromLee Harr <missive@hotmail.com>
Date2011-08-03 20:32 +0430
Subjectparsing 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.

 		 	   		  

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web