Created
July 10, 2011 14:10
-
-
Save aliles/1074564 to your computer and use it in GitHub Desktop.
Syntactic sugar to replace '__name__' idiom with function call
This file contains hidden or 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
| import main | |
| if main.executed(): | |
| print 'Hello World' |
This file contains hidden or 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
| if __name__ == '__main__': | |
| print 'Hello World' |
This file contains hidden or 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
| "Convenience function for programs 'main'." | |
| import inspect | |
| def executed(_level=1): | |
| """Return True if called in a module that is executed. | |
| Inspects the '__name__' in the stack frame of the caller, comparing it | |
| to '__main__'. Thus allowing the Python idiom: | |
| >>> if __name__ == '__main__': | |
| ... pass | |
| To be replace with: | |
| >>> if executed(): | |
| ... pass | |
| """ | |
| stack = inspect.stack() | |
| if len(stack) < _level: | |
| return False | |
| frame = stack[_level][0] | |
| if not inspect.isframe(frame): | |
| return False | |
| return frame.f_globals['__name__'] == '__main__' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment