Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published attech.serhatteker.com on

     

What does if __name__ == "__main__" do in Python?

An introduction to the __name__ variable

You probably seen the__name__ variable if you've gone through some python open source code. For instance below:

#!/usr/bin/env python3# -*- coding: utf-8 -*-importloggingimportosfromloggingimportFileHandlerfromloggingimportFormatterfromflaskimportFlaskfromflaskimportrender_templatefromflaskimportrequestfromformsimport*app=Flask(__name__)app.config.from_object("config")@app.route("/")defindex():returnrender_template("index.html")@app.route("/login")deflogin():form=LoginForm(request.form)returnrender_template("forms/login.html",form=form)@app.route("/register")defregister():form=RegisterForm(request.form)returnrender_template("forms/register.html",form=form)@app.errorhandler(404)defnot_found_error(error):returnrender_template("errors/404.html"),404ifnotapp.debug:file_handler=FileHandler("error.log")file_handler.setFormatter(Formatter("%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]"))app.logger.setLevel(logging.INFO)file_handler.setLevel(logging.INFO)app.logger.addHandler(file_handler)app.logger.info("errors")if__name__=="__main__":port=int(os.environ.get("PORT",5000))app.run(host="127.0.0.1",port=port)
Enter fullscreen modeExit fullscreen mode

Whenever the python interpreter reads a source file, it does two things:

  • sets a few special/global variables like__name__, then;
  • executes all of the code found in the file.

Why is the __name__ variable used?

The__name__ is a special python variable. It gets it's value depending on how we execute the containing module.

Sometimes you write a module with functions that might be useful in other module as well. In python, you can import that module into another module.

Thanks to this special variable, you can decide whether you want to run the the whole module. Or you want to import the functions defined in the module.

To grasp the context more vividly let see some use case examples.

Use Cases

Let's assume that we have module which has a simple function calledget_max() to get the maximum integer in a given array:

#!/usr/bin/env python3# -*- coding: utf-8 -*-# module_one.pydefget_max(array:list)->int:returnmax(array)print("Hello Module 1")array_example=[9,0,1,-6,3]# Calling the functionprint(f"max int:{get_max(array=array_example)}")
Enter fullscreen modeExit fullscreen mode

if we run this module we get the below result:

$python module_one.pyHello Module 1max int: 9
Enter fullscreen modeExit fullscreen mode

Case 1

So now assume that we need thisget_max() function from other module that we write:

#!/usr/bin/env python3# -*- coding: utf-8 -*-# module_two.pyimportmodule_oneprint("Hello Module 2")array_example=[3,17,-28,4]print(f"max int:{module_one.get_max(array=array_example)}")
Enter fullscreen modeExit fullscreen mode

If we now run themodule_two.py we get the output:

$python module_two.pyHello Module 1max int: 9Hello Module 2max int: 17
Enter fullscreen modeExit fullscreen mode

According to our program, the output should be "17" because the
onlyget_max() function is called. But the whole module is imported.

Case 2

To overcome this we useif __name__ == “__main__”. The extra line of codes written after functionget_max() inmodule_one.py is kept inside of it so it won't be executed while the function is imported inmodule_two.py.

Now update ourmodule_one.py like below:

#!/usr/bin/env python3# -*- coding: utf-8 -*-# module_one.pydefget_max(array:list)->int:returnmax(array)if__name__=="__main__":print("Hello Module 1")array_example=[9,0,1,-6,3]# Calling the functionprint(f"max int:{get_max(array=array_example)}")
Enter fullscreen modeExit fullscreen mode

Now run themodule_two.py:

$python module_two.pyHello Module 2max int: 17
Enter fullscreen modeExit fullscreen mode

You see that after usingif __name__ == “__main__” the unreletad codes will not be used bymodule_two.py.

Conclusion

After all that we understand that what doesif __name__ == “__main__” do in python; it prevents certain code to run if any other file import it.

All done!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:go:js |
  • Location
    127.0.0.1
  • Work
    Software Engineer
  • Joined

More fromSerhat Teker

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp