- Python __name__
- What’s Python __name__ ?
- Python __name__ variable example
- Summary
- Зачем __name__ == «__main__»?
- What’s in a (Python’s) __name__?
- Why is the _ _name_ _ variable used?
- What values can the __name__ variable contain?
- Scenario 1 — Run the script
- Scenario 2 — Import the script in another script
- Conclusion
- Специальная переменная __name__ в Python
- Комментарии ( 0 ):
Python __name__
Summary: in this tutorial, you’ll learn about the Python __name__ variable and how to use it effectively in modules.
What’s Python __name__ ?
If you have gone through Python code, you’ve likely seen the __name__ variable like the following:
if __name__ == '__main__': main()
Code language: Python (python)
And you might wonder what the __name__ variable is.
Since the __name__ variable has double underscores at both sides, it’s called dunder name. The dunder stands for double underscores
The __name__ is a special variable in Python. It’s special because Python assigns a different value to it depending on how its containing script executes.
When you import a module, Python executes the file associated with the module.
Often, you want to write a script that can be executed directly or imported as a module. The __name__ variable allows you to do that.
When you run the script directly, Python sets the __name__ variable to ‘__main__’ .
However, if you import a file as a module, Python sets the module name to the __name__ variable.
Python __name__ variable example
First, create a new module called billing that has two functions: calculate_tax() and print_billing_doc() . In addition, add a statement that prints out the __name__ variable to the screen:
def calculate_tax(price, tax): return price * tax def print_billing_doc(): tax_rate = 0.1 products = ['name'
: 'Book', 'price': 30>, 'name': 'Pen', 'price': 5>] # print billing header print(f'Name\tPrice\tTax') # print the billing item for product in products: tax = calculate_tax(product['price'], tax_rate) print(f"'name' ]>\t'price' ]>\t ") print(__name__)Code language: Python (python)
Second, create a new file called app.py and import the billing module:
import billing
Code language: Python (python)
When you execute the app.py :
> python app.py
Code language: CSS (css)
…the __name__ variable shows the following value:
billing
Code language: Python (python)
It means that Python does execute the billing.py file when you import the billing module to the app.py file.
The __name__ variable in the app.py set to the module name which is billing .
If you execute the billing.py as a script directly:
> python billing.py
Code language: CSS (css)
… you’ll see the following output:
__main__
Code language: Python (python)
In this case the value of the __name__ variable is ‘__main__’ inside the billing.py .
Therefore, the __name__ variable allows you to check when the file is executed directly or imported as a module.
For example, to execute the print_billing_doc() function when the billing.py executes directly as a script, you can add the following statement to the billing.py module:
if __name__ == '__main__': print_billing_doc()
Code language: Python (python)
Third, execute the billing.py as a script, you’ll see the following output:
Name Price Tax Book 30 3.0 Pen 5 0.5
Code language: Python (python)
However, when you execute the app.py , you won’t see the if block executed because the __name__ variable doesn’t set to the ‘__main__’ but ‘billing’ .
Summary
- Python assign the ‘__main__’ to the __name__ variable when you run the script directly and the module name if you import the script as a module.
Зачем __name__ == «__main__»?
В этой небольшой статье мы рассмотрим один из самых популярных «новичковых» вопросов — зачем нам конструкция if __name__ == «__main__».
Эта статья ориентирована на начинающих разработчиков, я пытаюсь объяснить тему максимально понятно и доступно. Поэтому где-то лукавлю, где-то преувеличиваю, но это для лучшего понимания, не кидайтесь ананасами 🙂
Прежде чем изучить конструкцию if __ name__ == __»main__«, необходимо знать несколько вещей:
- Интерпретатор Python выполняет весь код, который сможет найти в файле.
- Когда Python запускает «исходный файл» в качестве основной программы, он присваивает переменной __name__ значение __main__
В языках программирования существует такое понятие, как точка входа. В некоторых языках программирования (C, C#, Go) конструкция if __name__ = не требуется, потому что в самом начале разработки задается точка входа, без нее компилятор выдаст ошибку. Python же относится к этому лояльно и позволяет пользователю не указывать точку входу (Python в качестве точки входа считает первую строку), что может приводить к серьезным проблемам.
Также данная конструкция позволяет разделять файлы, чтобы они не пересекались при одновременной работе (при импорте модуля, либо при запуске самого модуля).
Например, у нас есть две программы:
- (test.py) выводит значение переменной __name__, а затем строку «Hello world».
- (test_2.py) импортирует модуль test.
Если в качестве исходной (откуда происходит запуск) программы мы выберем test.py, то на выводе получаем следующее:
Так как в качестве исходной программы мы выбрали test.py, интерпретатор Python присвоил значение переменной __name__: __main__. Теперь попробуем запустить test_2.py.
Как видим, вместо __main__ мы получили test. Почему это произошло? Потому что мы запустили модуль test, в котором есть строка print(__name__), но так как мы запустили этот код из другой программы (test_2.py), интерпретатор не вывел __main__.
Проще говоря, если мы запускаем программу через «побочную» программу, то переменной __name__ не будет задаваться значение __main__, что позволяет избежать лишнего срабатывания кода. Например:
Мы запустили файл test.py и получили на вывод результат сложения двух чисел и их разность. Также в конце вывели строку, говорящую, что запуск выполнен с помощью test.py. Если же мы импортирует этот модуль в программу test_2.py, то получим на вывод следующее:
А именно сообщение, что мы выполнили действия с помощью test.py, хотя в действительности это не так, ведь мы использовали test_2.py, а не test.py. Чтобы избежать подобного «лишнего» срабатывания фрагментов кода, необходимо в исходном файле (модуле) дописать конструкцию if __name__ == “__main__”. Должно получиться вот так:
Теперь при импортировании модуля test в test_2.py будет выполняться проверка значения переменной __name__. Запускаем наш test_2.py и видим, что теперь срабатывания print(“успешно выполнено с помощью test.py”) не произошло.
Благодарю за прочтение статьи, надеюсь вы подчерпнули из неё что-то новое.
Пишите в комменты какую тему разобрать в следующий раз, всем добра!
What’s in a (Python’s) __name__?
You’ve most likely seen the __name__ variable when you’ve gone through Python code. Below you see an example code snippet of how it may look:
if __name__ == '__main__': main()
In this article, I want to show you how you can make use of this variable to create modules in Python.
Why is the _ _name_ _ variable used?
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script.
Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
Thanks to this special variable, you can decide whether you want to run the script. Or that you want to import the functions defined in the script.
What values can the __name__ variable contain?
When you run your script, the __name__ variable equals __main__ . When you import the containing script, it will contain the name of the script.
Let us take a look at these two use cases and describe the process with two illustrations.
Scenario 1 — Run the script
Suppose we wrote the script nameScript.py as follows:
def myFunction(): print 'The value of __name__ is ' + __name__
if __name__ == '__main__': main()
If you run nameScript.py, the process below is followed.
Before all other code is run, the __name__ variable is set to __main__. After that, the main and myFunction def statements are run. Because the condition evaluates to true, the main function is called. This, in turn, calls myFunction. This prints out the value of __main__ .
Scenario 2 — Import the script in another script
If we want to re-use myFunction in another script, for example importingScript.py , we can import nameScript.py as a module.
The code in importingScript.py could be as follows:
We then have two scopes: one of importingScript and the second scope of nameScript . In the illustration, you’ll see how it differs from the first use case.
In importingScript.py the __name__ variable is set to __main__. By importing nameScript, Python starts looking for a file by adding .py to the module name. It then runs the code contained in the imported file.
But this time it is set to nameScript. Again the def statements for main and myFunction are run. But, now the condition evaluates to false and main is not called.
In importingScript.py we call myFunction which outputs nameScript. NameScript is known to myFunction when that function was defined.
If you would print __name__ in the importingScript, this would output __main__ . The reason for this is that Python uses the value known in the scope of importingScript.
Conclusion
In this short article, I explained how you can use the __name__ variable to write modules. You can also run these modules on their own. This can be done by making use of how the values of these variables change depending on where they occur.
Специальная переменная __name__ в Python
Когда интерпретатор Python читает файл, то сначала он устанавливает несколько специальных переменных. Затем выполняет код из файла.
Одной из таких переменных является __ name __.
В этой статье, Вы узнаете, как использовать специальную переменную __ name __, и почему она так важна.
Файлы Python называются модулями, и обозначаются расширением .py файл. Модуль может определять функции, классы и переменные.
Так что, когда интерпретатор обрабатывает модуль, переменная __ name __, будет установлена как __ main __ если модуль, который выполняется является основной программой.
Но если код импортирует модуль из другого модуля, то переменная __ name __ будет установлена на имя этого модуля.
Рассмотрим на примере вышесказанное. Создадим модуль Python с именем mod_one.py и вставим в него следующий код:
print(«Module one __name__ is: «.format(__name__))
Запустив этот файл, вы увидите именно то, о чем говорили. Переменная __ name __ устанавливается как __ main __:
# вывод Module one __name__ is: __main__
Теперь добавим еще один файл с именем mod_two.py и вставим следующий код:
print(«Module two __name__ is: » .format(__name__))
Кроме того, немного изменим код в mode_one.py, добавив импорт модуля mod_two:
print(«Module one __name__ is: «.format(__name__))
Запуск нашего кода mod_one еще раз покажет, что переменная __ name __ в mod_one не изменилась и по-прежнему остается установленной в __ main __. Но теперь переменная __ name __ для mod_two задается как имя ее модуля, следовательно, mod_two.
# вывод
Module two __name__ is: mod_two
Module one __name__ is: __main__
Но запустите mod_two напрямую, и вы увидите, что его имя установлено на _ main_:
Module two __name__ is: __main__
Часто в программах используется связка:
Здесь мы говорим программе, выполнить код если запущенный модуль есть основная программа.
Таким образом, сочетая __ name __ с условной конструкцией, мы можем управлять поведением наших модулей так, как нам это нужно.
Создано 22.12.2020 08:51:23
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.