Skip to content

Instantly share code, notes, and snippets.

@aliles
Created July 10, 2011 14:10
Show Gist options
  • Save aliles/1074564 to your computer and use it in GitHub Desktop.
Save aliles/1074564 to your computer and use it in GitHub Desktop.
Syntactic sugar to replace '__name__' idiom with function call
import main
if main.executed():
print 'Hello World'
if __name__ == '__main__':
print 'Hello World'
"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