0

I have a script which requires some environment variables to be set in order to work.

I am looking for a way to load the required .env files only when it is run as a standalone script. The variables are expected to be present if the script is imported by another program and it should not explicitly load the .env files.

The solution I came up with was having an additional if __name__ == "__main__" statement at the top of the script but I have never seen this done before.

How else can I solve this problem?

jacob
  • 160
  • 8
  • It doesn't answer your question, but what's wrong with your solution? This is exactly how you check if the file has been run as a standalone script. – kszl Mar 22 '21 at 23:20
  • @kszl I have never seen `if __name__ == "__main__"` statement used anywhere other than at the bottom of the script, so I just wanted to double check with the community. Also my solution would require me to add the statements twice (at the top and bottom; can't be avoided), so it feels a little inelegant. – jacob Mar 23 '21 at 00:24
  • There's little magic to it. `__name__` is just a special variable name interpreter sets for you. If the script has been run manually, that var is set to `"__main__"`. It's a script, so wrapping anything in a class or function won't do anything. You actually need a top level statement that does something. So it's usually at the end, after you initialize and declare everything. You can also do something like `is_script = __name__ == "__main__"` and use that if you don't want it twice. You can read more about it in eg here https://stackoverflow.com/questions/419163/what-does-if-name-main-do – kszl Mar 23 '21 at 00:39

0 Answers0