I have Python scripts that use the if __name__ == \'__main__\' trick to have some code only run when the script is called as a script and not when it is loaded
if __name__ == \'__main__\'
When working from within Emacs (which I assume is close to what you get with %edit), I usually use this trick:
%edit
if __name__ == '__main__' and '__file__' in globals(): # do what you need
For obvious reasons, __file__ is defined only for import'ed modules, and not for interactive shell.
__file__
import