Import or Execute Pattern in Python

1. import or execute pattern: name & main

  • in python, there are specially named bindings __name__ and __main__ allowing us to detect whether a module is
  • run as a script from a shell
  • imported into another module from the REPL
  • when you add print(__name__) at the end of the module, the module name is printed during the first import
  • if (and only if) the function with print(__name__) in the module is called from the shell with python script.py the shell return
▶ python script.py
__main__
  • you can modify the behavior so that the module is
  • executed from a shell
  • loaded from the REPL

2. syntax

  • add the following at the end of the script and if you call if from the shell and not from the REPL, the script executes immediately
if __name__ == "__main__":
FUNCTION_TO_BE_EXECUTED()

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why are we not using one type of Algorithm to solve problem?

Tech Predictions of Enterprise Application Software for 2020

Ruby: Foundational Knowhow(to me) ep.2

This Week In TurtleCoin (AUG 27, 2018)

How we ended up paying thousands of dollars to save pennies. #

Cost Explorer

OAuth Authentication in MuleSoft without API Manager

CS50x — Week 5

Maintenance and repair of lifting chain

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

How Does Python Locate Modules And Packages

Positional Only Arguments In Python

How To Use Reduce Function In Python

Why Import Of Sibling Packages Does Not Always Work In Python