Last active
December 17, 2015 07:19
-
-
Save dpk/13f2867f84fe419704c6 to your computer and use it in GitHub Desktop.
utility functions to make `if __name__ is "__main__":` less painful in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright David Kendal, 2013 | |
# You may redistribute this code, modified or unmodified, provided that this article is preserved in its entirety. | |
# Like all software, and information generally, this work is without warranty. | |
import inspect | |
# "if isscript():" is "if __name__ is '__main__':" | |
def isscript(frames=1): | |
callers = inspect.getouterframes(inspect.currentframe()) | |
return callers[frames][0].f_globals['__name__'] == '__main__' | |
# "@script" / "def main():" is "if __name__ is '__main__':" | |
def script(main): | |
if isscript(2): | |
return main() | |
# "@noscript" / "def main():" is "if __name__ != '__main__':" | |
def noscript(main): | |
if not isscript(2): | |
return main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment