__main__ — Top-level code environment (2023)

In Python, the special name __main__ is used for two important constructs:

  1. the name of the top-level environment of the program, which can bechecked using the __name__ == '__main__' expression; and

  2. the __main__.py file in Python packages.

Both of these mechanisms are related to Python modules; how users interact withthem and how they interact with each other. They are explained in detailbelow. If you’re new to Python modules, see the tutorial sectionModules for an introduction.

__name__ == '__main__'

When a Python module or package is imported, __name__ is set to themodule’s name. Usually, this is the name of the Python file itself without the.py extension:

>>> import configparser>>> configparser.__name__'configparser'

If the file is part of a package, __name__ will also include the parentpackage’s path:

>>> from concurrent.futures import process>>> process.__name__'concurrent.futures.process'

However, if the module is executed in the top-level code environment,its __name__ is set to the string '__main__'.

What is the “top-level code environment”?

__main__ is the name of the environment where top-level code is run.“Top-level code” is the first user-specified Python module that starts running.It’s “top-level” because it imports all other modules that the program needs.Sometimes “top-level code” is called an entry point to the application.

The top-level code environment can be:

  • the scope of an interactive prompt:

    >>> __name__'__main__'
  • the Python module passed to the Python interpreter as a file argument:

    (Video) Python Tutorial: if __name__ == '__main__'

    $ python3 helloworld.pyHello, world!
  • the Python module or package passed to the Python interpreter with the-m argument:

    $ python3 -m tarfileusage: tarfile.py [-h] [-v] (...)
  • Python code read by the Python interpreter from standard input:

    $ echo "import this" | python3The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit....
  • Python code passed to the Python interpreter with the -c argument:

    $ python3 -c "import this"The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit....

In each of these situations, the top-level module’s __name__ is set to'__main__'.

As a result, a module can discover whether or not it is running in thetop-level environment by checking its own __name__, which allows a commonidiom for conditionally executing code when the module is not initialized froman import statement:

if __name__ == '__main__': # Execute when the module is not initialized from an import statement. ...
(Video) If __name__ == "__main__" for Python Developers

See also

For a more detailed look at how __name__ is set in all situations, seethe tutorial section Modules.

Idiomatic Usage

Some modules contain code that is intended for script use only, like parsingcommand-line arguments or fetching data from standard input. If a modulelike this was imported from a different module, for example to unit testit, the script code would unintentionally execute as well.

This is where using the if __name__ == '__main__' code block comes inhandy. Code within this block won’t run unless the module is executed in thetop-level environment.

Putting as few statements as possible in the block below if __name___ =='__main__' can improve code clarity and correctness. Most often, a functionnamed main encapsulates the program’s primary behavior:

# echo.pyimport shleximport sysdef echo(phrase: str) -> None: """A dummy wrapper around print.""" # for demonstration purposes, you can imagine that there is some # valuable and reusable logic inside this function print(phrase)def main() -> int: """Echo the input arguments to standard output""" phrase = shlex.join(sys.argv) echo(phrase) return 0if __name__ == '__main__': sys.exit(main()) # next section explains the use of sys.exit

Note that if the module didn’t encapsulate code inside the main functionbut instead put it directly within the if __name__ == '__main__' block,the phrase variable would be global to the entire module. This iserror-prone as other functions within the module could be unintentionally usingthe global variable instead of a local name. A main function solves thisproblem.

Using a main function has the added benefit of the echo function itselfbeing isolated and importable elsewhere. When echo.py is imported, theecho and main functions will be defined, but neither of them will becalled, because __name__ != '__main__'.

Packaging Considerations

main functions are often used to create command-line tools by specifyingthem as entry points for console scripts. When this is done,pip inserts the function call into a template script,where the return value of main is passed into sys.exit().For example:

sys.exit(main())

Since the call to main is wrapped in sys.exit(), the expectation isthat your function will return some value acceptable as an input tosys.exit(); typically, an integer or None (which is implicitlyreturned if your function does not have a return statement).

By proactively following this convention ourselves, our module will have thesame behavior when run directly (i.e. python3 echo.py) as it will have ifwe later package it as a console script entry-point in a pip-installablepackage.

In particular, be careful about returning strings from your main function.sys.exit() will interpret a string argument as a failure message, soyour program will have an exit code of 1, indicating failure, and thestring will be written to sys.stderr. The echo.py example fromearlier exemplifies using the sys.exit(main()) convention.

See also

Python Packaging User Guidecontains a collection of tutorials and references on how to distribute andinstall Python packages with modern tools.

(Video) Python Tutorial Advanced (Modules) #1: __main__1 in Python (if __name__ == '__main__')

__main__.py in Python Packages

If you are not familiar with Python packages, see section Packagesof the tutorial. Most commonly, the __main__.py file is used to providea command-line interface for a package. Consider the following hypotheticalpackage, “bandclass”:

bandclass ├── __init__.py ├── __main__.py └── student.py

__main__.py will be executed when the package itself is invokeddirectly from the command line using the -m flag. For example:

$ python3 -m bandclass

This command will cause __main__.py to run. How you utilize this mechanismwill depend on the nature of the package you are writing, but in thishypothetical case, it might make sense to allow the teacher to search forstudents:

# bandclass/__main__.pyimport sysfrom .student import search_studentsstudent_name = sys.argv[2] if len(sys.argv) >= 2 else ''print(f'Found student: {search_students(student_name)}')

Note that from .student import search_students is an example of a relativeimport. This import style can be used when referencing modules within apackage. For more details, see Intra-package References in theModules section of the tutorial.

Idiomatic Usage

The contents of __main__.py typically isn’t fenced withif __name__ == '__main__' blocks. Instead, those files are kept short,functions to execute from other modules. Those other modules can then beeasily unit-tested and are properly reusable.

If used, an if __name__ == '__main__' block will still work as expectedfor a __main__.py file within a package, because its __name__attribute will include the package’s path if imported:

>>> import asyncio.__main__>>> asyncio.__main__.__name__'asyncio.__main__'

This won’t work for __main__.py files in the root directory of a .zip filethough. Hence, for consistency, minimal __main__.py like the venvone mentioned below are preferred.

See also

See venv for an example of a package with a minimal __main__.pyin the standard library. It doesn’t contain a if __name__ == '__main__'block. You can invoke it with python3 -m venv [directory].

See runpy for more details on the -m flag to theinterpreter executable.

(Video) if __name__ == "__main__" : main() top level script #python #script

See zipapp for how to run applications packaged as .zip files. Inthis case Python looks for a __main__.py file in the root directory ofthe archive.

import __main__

Regardless of which module a Python program was started with, other modulesrunning within that same program can import the top-level environment’s scope(namespace) by importing the __main__ module. This doesn’t importa __main__.py file but rather whichever module that received the specialname '__main__'.

Here is an example module that consumes the __main__ namespace:

# namely.pyimport __main__def did_user_define_their_name(): return 'my_name' in dir(__main__)def print_user_name(): if not did_user_define_their_name(): raise ValueError('Define the variable `my_name`!') if '__file__' in dir(__main__): print(__main__.my_name, "found in file", __main__.__file__) else: print(__main__.my_name)

Example usage of this module could be as follows:

# start.pyimport sysfrom namely import print_user_name# my_name = "Dinsdale"def main(): try: print_user_name() except ValueError as ve: return str(ve)if __name__ == "__main__": sys.exit(main())

Now, if we started our program, the result would look like this:

$ python3 start.pyDefine the variable `my_name`!

The exit code of the program would be 1, indicating an error. Uncommenting theline with my_name = "Dinsdale" fixes the program and now it exits withstatus code 0, indicating success:

$ python3 start.pyDinsdale found in file /path/to/start.py

Note that importing __main__ doesn’t cause any issues with unintentionallyrunning top-level code meant for script use which is put in theif __name__ == "__main__" block of the start module. Why does this work?

Python inserts an empty __main__ module in sys.modules atinterpreter startup, and populates it by running top-level code. In our examplethis is the start module which runs line by line and imports namely.In turn, namely imports __main__ (which is really start). That’s animport cycle! Fortunately, since the partially populated __main__module is present in sys.modules, Python passes that to namely.See Special considerations for __main__ in theimport system’s reference for details on how this works.

The Python REPL is another example of a “top-level environment”, so anythingdefined in the REPL becomes part of the __main__ scope:

>>> import namely>>> namely.did_user_define_their_name()False>>> namely.print_user_name()Traceback (most recent call last):...ValueError: Define the variable `my_name`!>>> my_name = 'Jabberwocky'>>> namely.did_user_define_their_name()True>>> namely.print_user_name()Jabberwocky
(Video) Understanding if __name__ == “__main__” in Python | Python Main Function with Examples

Note that in this case the __main__ scope doesn’t contain a __file__attribute as it’s interactive.

The __main__ scope is used in the implementation of pdb andrlcompleter.

FAQs

What is the meaning of if __ name __ == '__ main __' in Python? ›

In Short: It Allows You to Execute Code When the File Runs as a Script, but Not When It's Imported as a Module. For most practical purposes, you can think of the conditional block that you open with if __name__ == "__main__" as a way to store code that should only run when your file is executed as a script.

What is the use of __ main __ in Python? ›

What does the if __name__ == “__main__”: do? Before executing code, Python interpreter reads source file and define few special variables/global variables. 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__”.

What is __ all __ in Python? ›

A list of strings that define what variables have to be imported to another file is known as __all__ in Python. The variables which are declared in that list can only be used in another file after importing this file, the rest variables if called will throw an error.

What does __ init __ file do in Python? ›

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

What is __ in Python called? ›

Single standalone underscore _ is a valid character for a Python identifier, so it can be used as a variable name. According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation. It is stored in the builtin module. Here is an example.

Is Main () required? ›

This is nothing but the main function, or main() as it is usually denoted. It essentially serves as a starting point for the execution of a program. In Python, it is not necessary to define the main function every time you write a program.

What does __ name __ means? ›

__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.

What is the main function of the __ init __ method? ›

The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What does __ class __ mean in Python? ›

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

What is the difference between _ and __ in Python? ›

Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).

Does __ init __ run automatically? ›

The code in __init__.py is run whenever you import anything from the package. That includes importing other modules in that package.

Is __ init __ necessary in Python? ›

__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor. The __init__ method can be called when an object is created from the class, and access is required to initialize the attributes of the class.

Can I import __ init __? ›

There are two types of packages in python, regular and namespace packages. The former requires __init__.py file whereas the latter does not. Any directory with an init python file is marked as a package by python and can be imported.

What is '__ main __'? ›

__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

What is main () in coding? ›

The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.

What is __ main __ py file? ›

__main__.py is used for python programs in zip files. The __main__.py file will be executed when the zip file in run. For example, if the zip file was as such: test. zip __main__.py. and the contents of __main__.py was import sys print "hello %s" % sys.argv[1]

What are __ variables in Python? ›

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. But the data itself is still contained within the object. For example: >>> >>> n = 300.

What does __ mean in coding? ›

One Leading Underscore “_a”

If any programmer is seeing the code or reviewing the code, he must not change it. This variable starting with “_” states that this is used for internal use and the variable name is to be treated as private by the programmer. “_eggs” is the variables that mean it is for internal use only.

What is __ PATH __ in Python? ›

Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.

Can you run a program without main? ›

Yes, we can execute a java program without a main method by using a static block. Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block.

Is it possible to run program without main ()? ›

The answer is yes. We can write program, that has no main() function. In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true.

Can we compile without main? ›

We can write c program without using main() function. To do so, we need to use #define preprocessor directive. The C preprocessor is a micro processor that is used by compiler to transform your code before compilation.

Why _ is used in C? ›

The programmer uses a single underscore _ as the name for the second argument to the main function.

Is __ init __ a method? ›

"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.

What is self __ class __ __ name __ in Python? ›

self. __class__ is a reference to the type of the current instance. Throwing an exception here is like using an assert statement elsewhere in your code, it protects you from making silly mistakes. type() should be preferred over self.

How does __ call __ work? ›

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

What is __ set __ in Python? ›

Called to set the attribute on an instance instance of the owner class to a new value, value.

WHAT IS AN _ used for? ›

The underscore ( _ ) is also known as an understrike, underbar, or underline, and is a character that was originally on a typewriter keyboard and was used simply to underline words or numbers for emphasis. Today, the character is used to create visual spacing in a sequence of words where whitespace is not permitted.

Can you use _ in variable names? ›

A variable name must start with a letter or an underscore character (_) A variable name cannot start with a digit. A variable name can only contain alpha-numeric characters and underscores ( a-z, A-Z , 0-9 , and _ )

Do classes always need init? ›

Every class should have a method with the special name __init__. This initializer method is automatically called whenever a new instance of Point is created. It gives the programmer the opportunity to set up the attributes required within the new instance by giving them their initial state/values.

Can init be overridden? ›

Overriding init()

When extending GenericServlet or HttpServlet, you must either override init(ServletConfig) to first call super. init(ServletConfig) or simply override the init() method that takes no arguments.

Should init file be empty? ›

The answer to the question is yes, an __init__.py file can be empty. In fact, if you do not have a specific use case that requires you to include code in your __init__.py file, then your __init__.py file should be empty.

What happens if I don't use init in Python? ›

Originally Answered: What happens if you define a python class without an __init__ function? ? Nothing unintuitive happens. Your class will inherit the __ init__ method of its parent. definition), the child class will be initialized without any parameters.

Do you need self in __ init __? ›

__init__ does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods.

Why initialization is important in Python? ›

The important thing about initialization in static typed languages is that you specify the nature of the variables. In Python, as in other languages, you do need to give variables values before you use them.

Does init return self? ›

The init() method defined in the NSObject class does no initialization; it simply returns self .

Can we override init in Python? ›

For simpler cases move the initialization into the superclass' __init__ method, preventing it being overridden. Additional initialization of subclass should be done in the __init__ method of the subclass. For more complex cases, it is advisable to use a static method or function to manage object creation.

What does def __ init __( self do? ›

What is def __init__ self in Python? A constructor is used initialize an object's state. In Python, _init_ behaves like a constructor for a class. _init_ is called whenever a classes' object is created.

What does __ mean in Python method? ›

1. Use in Interpreter. Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want.

What is main in Python? ›

In Python, the role of the main function is to act as the starting point of execution for any software program. The execution of the program starts only when the main function is defined in Python because the program executes only when it runs directly, and if it is imported as a module, then it will not run.

What is __ class __ Python? ›

It accepts an object whose type we want to find out as the first argument and returns the type or class of that object. We can also use the __class__ property of the object to find the type or class of the object. __class__ is an attribute on the object that refers to the class from which the object was created.

What is main () called? ›

In 'C', the "main" function is called by the operating system when the user runs the program and it is treated the same way as every function, it has a return type. Although you can call the main() function within itself and it is called recursion.

Do you need main () in Python? ›

In Python, it is not necessary to define the main function every time you write a program. This is because the Python interpreter executes from the top of the file unless a specific function is defined.

Videos

1. Importing Your Own Python Modules Properly
(NeuralNine)
2. Intermediate Python Tutorial: How to Use the __init__.py File
(Eric O Meehan)
3. __name__ and __main__ how to use in python
(M.A.Basith Qureshi)
4. If __name__==__main__ usage & necessity | Python Tutorials For Absolute Beginners In Hindi #46
(CodeWithHarry)
5. [ERROR FIXED] “Attempted relative import in non-package” even with __init__.py
(Finxter - Create Your Six-Figure Coding Business)
6. Make Your Python Code More Professional
(NeuralNine)
Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated: 12/09/2022

Views: 5815

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.