iNTERFACEWARE Products Manual > Installing and Using Chameleon > Using Python Scripting > Python Scripting Examples > Adding a Counter to a Python Script |
|
Looking for Iguana v.5 or v.6? Learn More or see the Help Center.
One tricky problem with using global variables in Python scripts in Chameleon is how to initialize them. For example, suppose that you want to define a counter in Python to assign a global message ID to each message that you generate. The following code will not work, as the globalMessageID variable needs to be initialized before it can be incremented:
However, if you try to initialize globalMessageID simply by assigning to it, it will be reset every time the script is called:
The solution is to use an exception handler to check whether globalMessageID is defined:
This code references the variable globalMessageID inside a try statement. If globalMessage is not yet defined, a NameError exception is detected, and Python jumps to the code inside the except NameError statement. This code sets globalMessageID to an initial value of 1.
|