Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

__main__ and __name__ in Python

A Program written in languages of C family (C, C++, Java, C# etc.) needs the main() function to indicate the starting point of execution.

In Python, on the other hand, there is no concept of the main() function, as it is an interpreter based language and can be equally used in an interactive shell. The Python program file with .py extension contains multiple statements. The execution of the Python program file starts from the first statement.

Python includes the special variable called __name__ that contains the scope of the code being executed as a string. __main__ is the name of the top-level scope in which top-level code executes.

For example, the scope of the code executed in the interpreter shell will be __main__, as shown below.

Python Shell
>>>__name__
'__main__'

All the functions and modules will be executed in the top-level scope __main___ in the interpreter shell.

Python Shell
>>> def f1():
	print(__name__)
>>> f1()

Even the inner functions are executed in the top-level scope __main__:

Python Shell
>>> def f1():
	print(__name__)
	def f2():
		print(__name__)
	f2()

	
>>> f1()
__main__
__main__

A Python file can contain multiple functions and statements that can be executed independently. For example, consider the following addition.py:

addition.py
def add(x,y):
    z=x+y
	print('add() executed under the scope: ', __name__)
    return z

x=input('Enter the first number to add: ')
y=input('Enter the secode number to add: ')
result = add(int(x),int(y))
print(x, '+', y,'=', result)
print('Code executed under the scope: ', __name__)

Python program file can be executed in the following ways:

  1. Use the command prompt/terminal to execute the Python file as a script.
  2. Import Python code from one file to another using the import statement
C:\Python37> python addition.py
Enter the first number to add: 3
Enter the secode number to add: 3
add() executed under the scope: __main__
3 + 3 = 6
Code executed under the scope: __main__

As you can see, the addition.py executed under the top-level scope __main__.

The addition.py file can be used as a module in another file or in interactive shell by importing it.

Let's see what happens when you import the addition module in the interactive shell.

Python Shell
>>> import addition
Enter the first number to add: 3
Enter the secode number to add: 3
add() executed under the scope:  addition
3 + 3 = 6
Code executed under the scope:  addition

Above, the import statement starts executing from the first statement. But, we only want to use the add() method and don't want to execute the other statements.

Here we can use the special variable __name__ to check the scope and execute the statements of the addition.py file only when it executes from the command prompt/terminal independently but not when imported it in some other file/module. Rewrite the addition.py, as shown below.

addition.py
def add(x, y):
    z=x+y
	print('add() executed under the scope: ', __name__)
    return z

if __name__ == '__main__':
    x=input('Enter the first number to add: ')
    y=input('Enter the secode number to add: ')
    result = add(int(x),int(y))
    print(x, '+', y,'=', result)
    print('Code executed under the scope: ', __name__)

Above, the if condition check that if the scope is __main__ then only execute the code that takes user's inputs and adds them.

Now, let's see what happens when we import the above addition module in the interactive shell.

Python Shell
>>> import addition
>>> addition.add(3,3)
add() executed under the scope:  addition
6

You can also use the from import statement, as shown below:

Python Shell
>>> from addition import add
>>> add(3,3)
add() executed under the scope:  addition
6

As you can see, because we used an if condition to check the scope, it does not execute user input codes after importing the addition module, because it executes under the module's scope, which is addition scope. It only imports the add() method. The same thing will happen when you import the addition module in other modules.

Now, let's see what happens when you execute it from the command prompt/terminal.

C:\Python37> python addition.py
Enter the first number to add: 3
Enter the secode number to add: 3
add() executed under the scope: __main__
3 + 3 = 6
Code executed under the scope: __main__

As you can see, it still executes the same code because of addition.py being executed in the top-level scope __main__.

Thus, value of the name allows the Python interpreter to determine whether a module is intended to be an executable script or not. If its value is main, the statements outside function definitions will be executed. If not, the contents of the module are populated in top-level module (or interpreter namespace) without the executable part.

Note: The Python script file executing from the command prompt/terminal will be executed under the top-level scope __main__ scope. However, importing a module will be executed under the module's own scope. So, the top-level scope will be __main__, and the second scope would be module's scope.

Thus, using the special variable __name__ and the top-level scope __main__ increases the reusability. The Python script file can be executed from the command prompt/termainal as an indipendent script as well as when imported as a module.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.