Last active
March 14, 2021 20:50
-
-
Save benoit-dubreuil/fd3769be002280f3a22315d58d9976a4 to your computer and use it in GitHub Desktop.
Python3 Function to Detect if the Caller Is the Main Source
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 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__' |
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
#!/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