1

I am trying to run a Python application on Google Cloud Run on GCP and the code includes an

if __name__ == '__main__':

statement. For some reason, the code after this statement does not run and

print(__name__ == '__main__')

returns 'False' while

print(__name__)

returns 'main'.

When I run the code in a Jupyter notebook,

print(__name__ == '__main__')

returns 'True' while

print(__name__)

returns '__main__'.

Why does (i) print(__name__ == '__main__') return 'False' and (ii) print(__name__) return 'main' when the code is run on Google Cloud Run? And how does one fix this issue?

2 Answers2

4

The value of __name__ depends on how the file is being used. Consider the following file named test.py:

# test.py
print(__name__)

If we run the file directly, we get:

$ python test.py
__main__

This will print "__main__" because the interpreter is running the file as the main program.

Instead, if we import the file:

$ python -c "import test"
test

This will print test as that's the name of the module we're importing.

I'm guessing that you have your Cloud Run application in a file named main.py, and that you're using gunicorn as an HTTP server. So when you specify something like:

CMD exec gunicorn --bind :$PORT main:app

This is telling gunicorn to import the app variable from the main.py file, and thus __name__ will always be "main" in that file.

Depending on what you're doing in this if __name__ == "__main__" block, you could eliminate this check entirely and run the code inside it whenever the file is imported instead.

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
1

Before executing code, Python interpreter reads source file and define few special variables/global variables, such as the __name__ global variable.

  • If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”.

  • If this file is being imported from another module, __name__ will be set to the module’s name.

Module’s name is available as value to __name__ global variable.

A module is a file containing Python definitions and statements.

The file name is the module name with the suffix .py appended.

Here you may find some examples in order to comprehend this process.

This might explain why when you run it from Jupyter notebook it is returning ‘true’ and whereas when it is run by the application on Cloud Run it is returning ‘false’.

Could you please specify how the script is being run and provide the code as requested by @John Hanley?