Question

I have a function that logs into a sensor via telnet/pexpect and acts as a data collector.

I don't want to rewrite the part that logs in, grabs the data, and parses out relevant output from it (pexpect). However, I need to do different things with this code and the data it gathers

For example, I may need to:

  • Time until the first reading is returned

  • Take the average of a varying number of sensor readings

  • Return the status (which is one piece of data) or return the sensor reading (which is a separate piece of data) from the output

Ultimately, it should still login and parse output the same and I want to use one code block for that part.

Higher up in the code, it's being used instantaneously. When I call it, I know what type of data I need to gather and that's that. Constructing objects is too clumsy.

My usage has outstripped adding more arguments to a single function.

Any ideas?

Was it helpful?

Solution

This is such a common situation, I'm surprised you haven't already done what everyone else does.

Refactor your function to decompose it into smaller functions.

Functions are objects, and can be passed as arguments to other functions.

def step1(): 
    whatever

def step2(): 
    whatever

def step2_alternative():
    whatever

def original( args ):
    step1()
    step2()

def revised( args, step2_choice ):
    step1()
    step2_choice()

Now you can do this.

revised( step2 )
revised( step2_alternative )

It's just OO programming with function objects.

OTHER TIPS

Could you pass a data processing function to the function you described as an argument?

That may be more or less elegant, depending on your taste. (Forgive me: I know nothing about pexpect, and I may even have misunderstood your question!)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top