Jim
Jim

Reputation: 83

How can I dynamically add local variables to dynamically created Python class methods

I'm creating instrument classes for use with pyvisa. Rather than manually convert every SCPI command (about 400) into methods, I'd like to just copy the command quick reference into a text file and have commands like this:

[SENSe:]TEMPerature:TRANsducer:RTD:RESistance[:REFerence]? [{MIN|MAX}]

Wind up as methods like this:

def temp_tran_rtd_res_qry(*args):
    <check for valid arguments>
    cmd = 'TEMPerature:TRANsducer:RTD:RESistance?'
    argstr = ''
    for arg in args:
        argstr += ' ' + arg
    return self.query(cmd + argstr)

I have a handle on parsing the commands, and I figured out how to use setattr() to create the methods with the correct names from a template function.

The part that's giving me trouble is where each method knows what to assign to cmd. I thought I might add the original strings to the class as attributes (named similar to the methods) and parse them on the fly in the methods, but for this, the methods to be able to retrieve class attributes based on their names (or something).

Upvotes: 3

Views: 237

Answers (1)

Jim
Jim

Reputation: 83

So, here's what I figured out:

>>> class A(object):
    pass

>>> a = A()
>>> a.  # Only default 'object' methods avaliable
>>> cmdstr = '[SENSe:]VOLTage[:DC]:RANGe[:UPPer] {<range>|MIN|MAX|DEF} '
>>> querystr = """def query(cls, *args): cmd = '{s}'; return command_handler(*args, cmdstr=cmd)"""
>>> exec(querystr.format(s=cmdstr))
>>> setattr(A, command_name(command_abridge(cmdstr)), classmethod(query))
>>> a.volt_rang()    # Autocomplete works
<results from command_handler()>

I can write a file parser into __init__ to add a method to the class for each command string in a text file and I can write a generic method to parse the arguments and build the command strings for the actual queries.

Upvotes: 1

Related Questions