I'm sure I should know the answer to this, but how would I exit a Gateway Tag Change script early? You can't use return
and I know it's not great to use sys.exit()
. So what other options are there, apart from a potentially very long if/else
block and moving to a project library?
e.g.
...
if exit_condition:
LOGGER.info('log something')
else:
....
potentially_lots_of_lines_of_more_code...._with_ugly_useless_indenting
I'd prefer to do something like:
...
if exit_condition:
LOGGER...
exit
...
lots_of_lines...
Edit: perhaps I should move this all into a project library... I didn't really want to since the scripts are VERY specific to the tag change events 
whats wrong with sys.exit?
Never even thought of using it in python, but I can tell you why I have mixed feelings about exit
in C:
It breaks the normal flow of your program.
Imagine you're looking at the main
function, see it's doing things before its final return... but it never happens and you don't know why. So you have to go and dig through the source, following the flow of the program, until you find where it took a path you didn't expect and exited early.
I've used it, because sometimes the alternative is messy and painful, but always made a point in those cases to make it as clear and explicit as possible, usually through a function placed near the main
that handled the exit in a single place.
Now I know python is not C, but I'd expect similar reasons to apply.
Make a def() in Tag change script, use return where needed and at the end (bottom of the Tag change script) call that def()...
4 Likes
Haha, that's genius, that would work. I did end up moving everything into a script library though, and I don't regret it
1 Like
Even if it's specific to certain tags I always find that it's better off in a script library anyways. It makes it much easier to look at your script and how it relates to other gateway scripts that you would also have in your script library.
I especially make sure to do it for message handling - I can see how I send the message, how the message handler gets it, and what it does all in one script makes trouble shooting much easier.
Don't do it. This invokes a whole bunch of import grief due to backwards-compatible legacy scoping.
Gateway events scripts should always be one-liners (approximately) delegating everything to a project library script. Never--yes, Never--use any def
in a gateway event.
5 Likes
This is something to store away in my tips and tricks 
Care to elaborate a little more?
Look for the numerous posts here where people have to include import system
inside their functions because of this particular phenomenon. Or any other top-level variable that is normally auto-included and available throughout out all class and function definitions. Or encountering cross-event contamination of variable assignments.
1 Like