You are designing a script that may be imported as a module in other scripts. What variable can you use to check whether the script has been imported as a module, or is running as the main script?

Answered on

In Python, you can determine whether a script is being run directly or imported as a module by examining the `__name__` variable. When a Python script is run, an implicitly declared special variable named `__name__` is set to `"__main__"` if the script is being run as the main program. If the script is imported as a module in another script, `__name__` is set to the name of the script/module.

Here's a typical pattern to use this variable in your script:

```python # mymodule.py

def some_function(): print("Function inside the module.")

if __name__ == "__main__": print("The script is run directly") # Code here will only execute if the script is run directly, not if it is imported. else: print("The script has been imported as a module") # Code here can handle what should happen when the module is imported. ```

When you import `mymodule` in another script like this:

```python # other_script.py

import mymodule ```

The message `"The script has been imported as a module"` will be printed, since `mymodule.py`'s `__name__` attribute will be set to `"mymodule"`.