Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for The if __name__ == "__main__" conditional in python
Osinachi Chukwujama
Osinachi Chukwujama

Posted on

     

The if __name__ == "__main__" conditional in python

TL;DR

When a module is imported into a script, the module's code is run when the script is run.
This is useful for unit testing

Like, most programming languages, python has special variables. A peculiar special variable in python is the __name__ variable.

When you have a script that can act as both a module and a script, you'd probably need this conditional statement.

One thing about python modules is that if imported, into a script all the code in that module is run when the script is run.

module.py

print("I am module.py")deffunc1():return"The first function was called"if__name__=="__main__":print(func1())# When this module (or script) is run this would be the outputIammodule.pyThefirstfunctionwascalled
Enter fullscreen modeExit fullscreen mode

script.py

importmoduleprint("I would be printed after'I am module.py'")# When this script is run, this would be the outputIammodule.pyIwouldbeprintedafter'I am module.py'# Note, func1 wasn't called
Enter fullscreen modeExit fullscreen mode

Now, let's assume we have a script with useful utility functions. We want to be able to test our script and also export it as a module. We would put our unit tests in the conditionalif __name__ == "__main__"

Try this out yourself. Investigate it. Then learn about unit testing in python. Thanks for reading.

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

Learning server-side development. Creating courses on educative.io
  • Location
    Owerri Nigeria
  • Education
    Federal University of Technology Owerri
  • Joined

More fromOsinachi Chukwujama

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