Skip to content

Instantly share code, notes, and snippets.

@benoit-dubreuil
Last active March 14, 2021 20:50
Show Gist options
  • Save benoit-dubreuil/fd3769be002280f3a22315d58d9976a4 to your computer and use it in GitHub Desktop.
Save benoit-dubreuil/fd3769be002280f3a22315d58d9976a4 to your computer and use it in GitHub Desktop.
Python3 Function to Detect if the Caller Is the Main Source
import inspect
from types import FrameType
from typing import cast
def is_caller_main() -> bool:
# See https://stackoverflow.com/a/57712700/
caller_frame = cast(FrameType, cast(FrameType, inspect.currentframe()).f_back)
caller_script_name = caller_frame.f_locals['__name__']
return caller_script_name == '__main__'
#!/usr/bin/env python3
# Use case
import main_utils
if main_utils.is_caller_main():
print('MAIN')
else:
print('NOT MAIN')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment