Determining Python function call context

Sometimes there’s a need for a function to behave one way when called from within its module by another member function, and then behave in some other way when called from outside the module. In other words, it needs to be context sensitive. One way to handle this in Python is to use default parameter values.

Let’s say that we have some code that controls the power to something using a multi-channel AC power controller. In the Python power control module there is a function called SetPower() that handles the power control for a single channel. There are also some parameters in a standard *.ini file that can be used to define the amount of time the code will delay after a channel is enabled. This is to allow the devices attached to the controller some time to stabilize. Another function in the module, called PowerOn(), calls the function SetPower() for each channel in a predefined sequence.

If SetPower() is called from outside the module (i.e. not as part of a power-up or power-down sequence), then we probably don’t want it to delay after commanding the AC controller to activate a particular channel. If it’s called by PowerOn() then we do want it to use the delay parameters. An easy way to handle this is to define a parameter for SetPower that is only used when the function is called from within its own module, like so:

def SetPower(channel, state, delay = False):

If we want to use SetPower() from, say, a control dialog, then we need only omit the delay parameter and it will default to False.

When calling SetPower() from the PowerOn() function, we set delay to True, like so:

rc = SetPower(channel, state, delay = True)

Naturally the call to SetPower would be within a loop structure of some kind, and the parameters channel and state would be assigned the appropriate values within the loop.

And that’s all there is to it.

0 Responses to “Determining Python function call context”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow Crankycode on

Little Buddy

An awesome little friend

Jordi the Sheltie passed away in 2008 at the ripe old age of 14. He was the most awesome dog I've ever known.


%d bloggers like this: