×

_name_ in Python

Introduction:

The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function like the C language. Before that, though, it will define a few unique variables. One such unique variable is __name__. If the source file is launched as the main program, the interpreter changes the value of the name variable to " main ". If this file is imported from another module, name will be set to the name of the module.

What is _name_ in Python?

_name__ is a built-in variable that evaluates the name of the current module.

Note: By combining it with an if statement, as demonstrated below, it may be used to determine if the current script is being executed independently or being imported into another script.

Code:

# Program1.py 
print ("Program1 __name__ = %s" %__name__) 
if __name__ == "__main__": 
    print ("Program1 is being run directly")
else: 
    print ("Program1 is being imported")

Output:

_name_ in Python

Why is the Variable "_name_" Used?

One of the unique Python variables is _name   . Depending on how we run the contained script, it derives its value.

There are occasions when you write a script that has functionalities that might be applied to other scripts as well. That script can be imported into another script in Python as a module.

You can choose whether to execute the script using this unique variable. Or perhaps you wish to import the script's defined functions.

What Types of Values may the Variable _name_  Hold?

The __name__ variable takes on the value __main__ when your script is executed. When you import the enclosed script, the name of the script will be shown.

Understanding This through an Example:

Make a script in Python called Script1.py, and add the following code to it:

Code:

#Script1.py
# A function is defined 
def Valuestored():
print('Value of __name__:', __name__)
Valuestored()

Output:

_name_ in Python

The value for the __name__ variable was set to __main__ when we ran the Script1.py script.

Let's now build another Python script called Script2.py to which you can import the previous one.

Code:

#Script2.py
# importingScript1.py
import Script1
Script1.Valuestored()

Output:

_name_ in Python

The Script1.py module's name variable's value was printed, therefore you can see from the output of the code above that the variable's value is Script1.

If __name__ == __main__ is Used:

If you want to restrict the execution of certain Python code to only when the script is run directly, use the if statement with the condition name == main .

As an example;

Code:

# importingScripy1.py
import Script1
if __name__ == __main__:
Script1.Valuestored()

Here, it is possible to tell whether the current module or script is running independently or not using the string main. The name variable has two underscores on either side of the name to indicate to the Python interpreter that it is a reserved or special term.

_name_ in Python: Example using Code:

It has already been mentioned that when we run a code file, the value of the name variable changes to main since the code is executed directly rather than being imported into another file.

Code:

#Code1.py
# A function is defined 
def Value():
print('Function is in Code1.')
    if __name__=="__main__":
Value()
print('Called from Code1.')
else:
print('Seems like Code1 is imported in some other file.')

Output:

_name_ in Python

Let's now create a new Python script file called Code2.py, import Code1.py into it, and attempt to invoke the function Values() that is defined in Code1.

Code:

import Code1
if __name__=='__main__':
Code1.Value()
print(' This is Called from Code2.')

Output:

_name_ in Python

When the import statement for Code1 was run inside Code2, the name variable had the value Code1 (the name of the module), but since Code2 was the first script to be run, it now has the value main.

Conclusion

  • The scope of the code being run is stored as a string in the Python special variable __name__.
  • In most programming languages, the main method or function is often utilised as the point at which any program is performed. But what about Python? The first line, which represents the program's indentation level 0, is often where a Python program (script) starts to run.
  • The creation of a named variable occurs before a Python program is run, though. This variable can be utilized in Python in place of the main method.
  • When you execute the script directly in Python, it assigns the '__main__' variable to the __name__ variable, and if you import the script as a module, it assigns the module name.

Related Topics

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Standard Scalar in Python

Python is a vast and open-source language that contains many libraries, modules, and functions. These functions in python are reusable codes where we don’t need to type the whole code...

4 minutes read.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Python and its advantages

What is Python? Python is an object-oriented programming language, a general-purpose programming language with a high level, and also an interpreted language that has an easy syntax and dynamic semantics. Python...

7 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.