[code sharing] descriptive keyword arguments

asked Nov 25 '4

likethevegetable gravatar image

updated Jan 15 '5

I'm stuck using PSSE 34, and have a strong dislike for passing arguments using intgar and realar. So I made a little helper function.

import re
def pssf(fun, *args, **kwargs):
    """
    pssf = pss function caller
    Call a psspy function with descriptive kw-args
    Eg. for machine_chng_2, we normally use intgar1=1 to changes the machine status, or realar1=100.0 to change the power (pg), like so:
        psspy.machine_chng_2(101, '1', intgar1=1, realar1=100.0)
    This function lets you do the following:
        pssf('machine_chng_2', 101, '1', stat=1, pg=100.0) 
    which I think is more readable.
    """
    fun = getattr(psspy, fun)
    doc = fun.__doc__
    kwargs_new = kwargs.copy()
    for k, v in kwargs.items():
        for t in 'INTGAR', 'REALAR', 'CHARAR':
            matches = re.search('^\s*' + t + '\((\d+)\)\s+' + k.upper() + ',', doc, re.MULTILINE)
            if matches:
                kwargs_new[t.lower() + matches.group(1)] = v
                kwargs_new.pop(k)
                break
    return fun(*args, **kwargs_new)

Do newer versions of PSSE solve this problem? Did I waste my time making this?

Comments

Very nice function that can be very useful! However variable s in not defined, I get an error when testing the function.

perolofl gravatar imageperolofl (Jan 15 '5)

Thanks for the feedback @perolofl. "s" should be "doc", I updated the example.

likethevegetable gravatar imagelikethevegetable (Jan 15 '5)

Now the script works without crash, but data is not updated. I tried in rev 33 and 35. The function is not replacing pg with realar1 and stat with intgar1.

perolofl gravatar imageperolofl (Jan 15 '5)

@perolofl Interesting, I just tested it in v34 py 2.7 and 3.7 and it works. If there is a documentation syntax difference between 33 and 34, that could be why.

likethevegetable gravatar imagelikethevegetable (Jan 15 '5)

@perolofl I fixed it, see the update. It was what I expected, the spacing in the documentation between versions is different. I changed it, should work with all versions now. FWIW I also added some other features if you're interested, eg. instead of passing `machine_chng_2` you can just pass `mach_`

likethevegetable gravatar imagelikethevegetable (Jan 15 '5)