Что такое global и nonlocal. Легкий способ получить UnboundLocalError

Python Russian
Python Russian

Как обещал в прошлом видео - рассмотрим ключевые слова global и nonlocal Особенности: 1) если мы пытаемся изменить какую-то переменную внутри функции, интерпретатор автоматически считает ее локальной, слова global/nonlocal нужны как информация интерпретатору, что переменная не локальна 2) оба ключевых слова НЕ нужны, если вам нужно только читать переменную, используйте их только для изменения 3) оба слова позволяют сразу перейти к поиску в нужном пространстве имен, nonlocal сразу переходит к поиску во внешних функциях (в который вложена текущая), global сразу переходит к поиску в глобальном пространстве имен. То есть nonlocal сразу идет в букву E, а global в букву G в аббревиатуре LEGB 4) global позволяет создать в глобальном пространстве имен переменную, которой там не было. Nonlocal работает только с уже существующими переменными 5) Nonlocal НЕ ищет в глобальном, а global во вложенных скоупах! Они не взаимозаменяемы 6) Есть редкие случаи, когда использование global оправдано, но в большинстве случаев и просто как хорошая практика - не стоит использовать global и nonlocal. Стоит отдавать предпочтение независимым, "чистым" функциям. Почитать: Learning Python, Fifth Edition by Mark Lutz, глава 17 https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python https://docs.python.org/3/reference/simple_stmts.html?highlight=global#the-global-statement https://docs.python.org/3/reference/simple_stmts.html?highlight=global#the-nonlocal-statement Присоединяйтесь к помощи каналу, будет интересно) ✔️Бусти https://boosty.to/python_russian/donate ✔️Юмани 410011506612886 Будь первым везде и всегда, включай уведомления о новых выпусках 🔔 Смотри там где удобно🤩 ✔️ https://vk.com/python_russian ✔️ https://boosty.to/python_russian ✔️ https://www.youtube.com/c/PythonRussian ✔️ https://t.me/python_russian ✔️ https://dzen.ru/python_russian ✔️ https://rutube.ru/channel/24346352/ #Python #PythonRussian #global #nonlocal #UnboundLocalError


Keywords (if available)
Comments

Users Comments

User Avatar
хочется обратить внимание, что если в глобальном скоупе переменная мутируемого типа данных, то для ее изменения не нужно писать global простой пример: a = [] def incr(): a.append(1) incr() incr() print(a) выведет [1, 1]
Related Videos

Related videos

Thumbnail

Юнит-тестирование. Использование unittest и coverage в PyCharm

Подписчики просили рассказать о юнит-тестировании, делаю первый шаг в этом направлении. Тесты нужно писать обязательно, это единственно...

By Python Russian

Duration: 42:50

Thumbnail

Basic Python 27: Global Variable | Local Variable | Nonlocal Variable in Python

Python Global, Local and Nonlocal variables: -------------------------------------------- Global Variables: ----------------- - A variable declared outside of the function or in global scope is known as a global variable. - This means that a global ...

By Питоновый финансовый анализ

Duration: 7:29

Thumbnail

Функции (global, nonlocal, замыкания) в Python

В данном видео рассмотрим принцип работы таких операторов, как global и nonlocal. А также механизм замыканий. Код урока доступен по следующим с...

By MADTeacher

Duration: 7:58

Thumbnail

#43. Области видимости переменных. Ключевые слова global и nonlocal | Python для начинающих

Обучающий курс: https://stepik.org/course/100707 Что такое глобальные и локальные переменные. Как они определяются и ведут себя. Ключевые слова global и nonl...

By SelfEdu - мир знаний с Сергеем Балакиревым

Duration: 14:49

Thumbnail

Don't use the global keyword in your Python program! The UnboundLocalError explained and fixed!

If you're new to Python, you might have encountered (and been confused by) the UnboundLocalError. I was the first time I encountered it! I explain the error and how to fix it in this video. Have fun learning Python with me! This channel is suita...

By Молодежный Python-магазин

Duration: 7:24

Thumbnail

Mastering Python's Scopes: Global, Local, and Nonlocal

In this video, you'll learn everything you need to know about Python's scopes and how they work. From basic concepts to advanced techniques, this tutorial covers everything you need to understand the visibility and accessibility of variable...

By Программирование Вопрос

Duration: 11:02

Thumbnail

Python 3 #18: области видимости переменных - global, nonlocal

Инфо-сайт: https://proproprogs.ru Глобальные и локальные переменные: как создаются и как используются. Ключевые слова global и nonlocal.

By Уборка с теплом

Duration: 8:39

Thumbnail

python2 using global bug ,UnboundLocalError local variable referenced before assignment

Traceback (most recent call last): File "./Module6_namespace_scoping_bug_hunting.py", line 10, in module AddNumber() File "./Module6_namespace_scoping_bug_hunting.py", line 4, in AddNumber Number = Number + 1 UnboundL...

By Python система

Duration: 1:59

Thumbnail

Python - Global, Local and Nonlocal Variables

Python - Global, Local and Nonlocal Variables Watch more Videos at https://www.tutorialspoint.com/videotutorials/index.htm Lecture By: Mr. Arnab Chakraborty, Tutorials Point India Private Limited

By Без сложностей: создание чат-ботов

Duration: 6:39

Thumbnail

Python Global, Local and Nonlocal variables| developersonline

Telegram: https://t.me/joindevelopersonline Mail: developersonline.org@gmail.com Github: https://github.com/tusharkhatriofficial Twitter: https://twitter.com/DamanKhatri_ Facebook Page: https://www.facebook.com/pages/catego... Website link - h...

By PythonУскорение

Duration: 8:50

Thumbnail

Python local global nonlocal variables | python tutorial for beginners | python coding variables

Python local global nonlocal variables | python tutorial for beginners | python coding variables Join this channel to get access to perks: https://www.youtube.com/channel/UC0nk24muIA7ix5z7DkpIGSg/join Please find link below to create git repo https...

By Питонские задачки для начинающих

Duration: 6:44

Thumbnail

Scopes in Python | LEGB rule | global and nonlocal keyword

This video explains Scopes in Python, the LEGB rule and the `global` and `nonlocal` keywords. Here is a link to the memes: https://github.com/iArunava/wiity-this-repo-has-memes Tip: Watch in 1.25x | 1.5x | 2.0x for faster learning :) Thanks for wa...

By Python: новая эпоха разработки

Duration: 9:39

Thumbnail
Thumbnail

Python 3: UnboundLocalError: local variable referenced before assignment

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn -- Music by Eric Matyas https://www.soundimage.org Track title: Puzzle Game 5 Looping -- Chapters 00:00 Question 00:30 Accepted answer (Score 103) 00:49 Answ...

By Алгоритмическая Эпопея

Duration: 4:52

Thumbnail

[Learn Tutorial| Python03] Maybe think of global, nonlocal, local variables in this way

#python #global #nonlocal #local #variables Maybe think of global, nonlocal, local variables in this way More: https://docs.python.org/3/tutorial/classes.html#tut-scopess Background sound: wind and wave from Baltic sea

By Кодовое Разнообразие

Duration: 2:37

Thumbnail
Thumbnail

Python - local, nonlocal and global variables

By Создание умных помощников: основы и практика

Duration: 11:41

Thumbnail

Variable Scope | Understanding the LEGB rule and global/nonlocal statements | Python Course 2023

In this Python Beginner Tutorial, we will learn variable Scopes in Python, We'll take a look in the LEGB rule, understand when to use global, nonlocal keywords in Python. In this Python Tutorial, we will be going over variable scope in Python. ...

By Питонские шаги в программировании для новичков

Duration: 28:43

Thumbnail

Python Tutorial #22 - Variable Scope (local, global, nonlocal) in Python Programming

Python Tutorial #22 - Variable Scope (local, global, nonlocal) in Python Programming for Beginners In this video by Programming for beginners we will see Variable Scope in Python Programming for Beginners, in Python tutorial for beginners series. Pyt...

By PythonLab

Duration: 9:37

Thumbnail