Shadows name from outer scope python что это
Перейти к содержимому

Shadows name from outer scope python что это

  • автор:

Shadows name from outer scope python что это

Last updated: Jun 29, 2023
Reading time · 3 min

banner

# Warning: Shadows name X from outer scope in PyCharm

The PyCharm warning «Shadows name ‘X’ from outer scope» is shown when you have a parameter of a function or a variable defined in a function that shadows a variable defined in the outer scope.

To resolve the issue, rename the variable or parameter so it doesn’t clash with the one from the outer scope.

Here is an example of when the warning is shown.

Copied!
site = 'bobbyhadz.com' # ⛔️ Shadows name 'site' from outer scope def print_site(site): print(site) # bobbyhadz.com print_site(site)

shadows name from outer scope

We have a variable named site that is defined in the global scope.

The print_site function takes a parameter named site and prints it.

The warning is shown because the name of the parameter ( site ) is the same as the name of the variable ( site ) in the outer scope.

This causes the two variables to clash.

One way to resolve the issue is to rename the function parameter (or the site variable from the outer scope).

Here is an example that renames the function parameter.

Copied!
site = 'bobbyhadz.com' def print_site(website): print(website) # bobbyhadz.com print_site(site)

rename function parameter

I renamed the function parameter from site to website to resolve the issue.

The name of the parameter no longer shadows the variable from the outer scope so the issue is resolved.

You can also rename the global variable to resolve the warning.

Copied!
website = 'bobbyhadz.com' def print_site(site): print(site) # bobbyhadz.com print_site(website)

rename outer scope variable to resolve warning

I renamed the outer scope variable to website and the function’s parameter is named site , so they no longer clash.

# Function parameter/variable sharing the same name as an outer scope variable

When the function’s parameter shares the same name as the outer scope variable, the outer scope variable becomes inaccessible (directly) inside the function.

Here is a code sample that better illustrates this.

Copied!
site = 'bobbyhadz.com' def print_site(): # ⛔️ Shadows name 'site' from outer scope site = 'google.com' print(site) # google.com print_site()

We declared a site variable in the outer scope and then declared a variable with the same name inside the function.

When we pass the site variable to the print() function, the variable from the local scope gets printed.

You cannot access the `site` variable from the outer scope inside the print_site function because the local variable with the same name shadows it.

To resolve the issue, you either have to rename the global variable or the local variable.

Copied!
site = 'bobbyhadz.com' def print_site(): website = 'google.com' print(website) # google.com print_site()

Now the names of the outer scope and local variables no longer clash, so the issue is resolved.

# Disabling the «Shadowing names from outer scopes» warning in PyCharm

If you want to disable the «Shadowing names from outer scopes» warning in PyCharm:

  1. Press Ctrl + Alt + S or click on File in the top menu and then select Settings.
  2. Click on Editor, then Inspections and search for shadowing names.
  3. Uncheck the Shadowing names from outer scopes checkbox and click on Apply and OK.

disable shadowing names from outer scope in pycharm

# Wrapping the outer scope variable in a function

An alternative way to resolve the warning is to wrap your outer scope variable in a function.

Copied!
def main(): site = 'bobbyhadz.com' print_site(site) def print_site(site): print(site) main()

The site variable is no longer defined in the global scope so it doesn’t shadow the parameter of the print_site function.

# Using a trailing underscore to differentiate between the two variables

A commonly used convention that you can use to solve the error is to add a trailing underscore after the name of the variable (or the name of the function parameter).

Copied!
site = 'bobbyhadz.com' def print_site(site_): print(site_) # bobbyhadz.com print_site(site)

The function parameter is named site_ instead of site .

Now the two names don’t clash so the warning is no longer shown.

I’ve also written a detailed guide on how to use global variables in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Delete or Change a Global Variable in a Function in Python
  • How to clear the Terminal and Console in PyCharm
  • Pycharm does not show a Matplotlib Plot issue [Solved]

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для экспертов
  • » Область видимости и ссылки на аргументы

#1 Авг. 3, 2015 21:52:58

ArtikUA Зарегистрирован: 2015-05-14 Сообщения: 8 Репутация: 0 Профиль Отправить e-mail

Область видимости и ссылки на аргументы

Есть словарь и две функции: первая переворачивает значение ключа name этого словаря, а вторая — делает все буквы заглавными:

def first(town): town['name'] = town['name'][::-1] return town def second(town): town['name'] = town['name'].upper() return town town = 'name': 'Moscow', 'population': '10000000'> town = first(town) town = second(town) print(town['name']) 

Всё работает отлично, но в каждом аргументе при объявлении функции IDE ругается на “Shadows name ‘town’ from outer scope”

И в самом деле, если мы сделаем так:

def first(): town['name'] = town['name'][::-1] def second(): town['name'] = town['name'].upper() town = 'name': 'Moscow', 'population': '10000000'> first() second() print(town['name']) 

То результат не изменится.
Почему функции видят то, что по идее должно быть за пределами области видимости?
Я ведь не делал global town
Как сделать что бы всё было на “чистых” функциях?

Отредактировано ArtikUA (Авг. 3, 2015 21:54:17)

#2 Авг. 3, 2015 23:43:36

JOHN_16 От: Россия, Петропавловск-Камчатск Зарегистрирован: 2010-03-22 Сообщения: 3292 Репутация: 221 Профиль Отправить e-mail

Область видимости и ссылки на аргументы

Потому что о реализации области видимости в Питоне вы толкьо слышали, а не изучали. Он работает ровно так как и положено. Книга Лутца “Програмируем с Python”(3 изд.) глава 16: Области видимости функции. Вырезка:

Разрешение имен: правило LEGB
Для инструкции def:
• Поиск имен ведется самое большее в четырех областях видимости:
локальной, затем в объемлющей функции (если таковая имеется),
затем в глобальной и, наконец, во встроенной.
По умолчанию операция присваивания создает локальные имена.
• Глобальные объявления отображают имена на область видимости
вмещающего модуля.
Другими словами, все имена, которым присваиваются значения
внутри инструкции def (или внутри выражения lambda, с которым мы
познакомимся позже), по умолчанию являются локальными; функции могут
использовать имена в лексически (т. е., физически) объемлющих
функциях и в глобальной области видимости, но чтобы иметь возможность
изменять их, они должны быть объявлены глобальными. Схема
разрешения имен в языке Python иногда называется правилом LEGB,
название которого состоит из первых букв названий областей видимости:
• Когда внутри функции выполняется обращение к неизвестному
имени, интерпретатор пытается отыскать его в четырех областях
видимости — в локальной (local, L), затем в локальной области
любой объемлющей инструкции def (enclosing, E) или в выражении
lambda, затем в глобальной (global, G) и, наконец, во встроенной
(built-in, Б). Поиск завершается, как только будет найдено первое
подходящее имя.
• Когда внутри функции выполняется операция присваивания (а не
обращение к имени внутри выражения), интерпретатор всегда
создает или изменяет имя в локальной области видимости, если в этой
функции оно не было объявлено глобальным.
• Когда выполняется присваивание имени за пределами функции (т.е.
на уровне модуля или в интерактивной оболочке), локальная область
видимости совпадает с глобальной — с пространством имен модуля.

Т.е. механизм поиска переменной с именем Foo и присваивание переменной имени Foo — существенно отличается.

Если брать определение чистой функции, то скорее всего так:

def first(value): return value[::1] town['name'] = first(town['name']) 

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

Как можно исправить такие ошибки?

Author24 — интернет-сервис помощи студентам

Как исправить такие ошибки
Как исправить такие ошибки? cc1plus: warnings being treated as errors Line 3: warning: ignoring.

Как исправить такие ошибки?
Создаю пустой проект в креаторе, при компиляции(4.6.4+mingw) пишет .

Ошибки в C++ Builder как можно исправить
Application->CreateForm(__classid(TForm1), &Form1); Ошибка Type name expected .

Как можно исправить ошибки в моем коде?
Цель кода: рандомно создаются буквенные массивы,из них отбираются и выводятся в ответ только.

Найти ошибки и исправить их, проанализировать полученные результаты и объяснить, почему они именно такие
Помогите,пожалуйста решить задачу, всей группой решить не можем) Постановка задачи Набрать.

How to fix “Shadows name from outer scope” in PyCharm

Pycharm Shadows Names

PyCharm is a hugely popular Python IDE developed by JetBrains. PyCharm supports pretty much anything you can think of when you mention a modern IDE, such as debugging, syntax highlighting, project management, smart prompt, automatic completion, unit testing, version control… In addition to that, PyCharm also provides advanced web development for Django, doing data science with Anaconda and even IronPython.

While working with PyCharm, you might encounter some warning, a few of them are not Python error messages. “Shadows name from outer scope” is one of the most common error message that spread confusion among new users. This article will explain why it happens and what you can do to avoid it.

Why does “Shadows name from outer scope” happens?

Let’s take the code snippets below as our example :

the_list = [1, 2, 3] def data_log(the_list): # Warning: "Shadows 'the_list' from outer scope print(the_list) data_log(the_list)

You can clearly see that in the first line we define the_list in the global scope, and inside the function data_log , we reused that name. Reusing names in and out of functions will be referred as “shadowing names” in PyCharm, therefore causes “Shadows name from outer scope”. This is just a warning and doesn’t make your code unable to run.

While there’s nothing wrong with the example and it runs just fine, it can be the beginning of strange behaviour if you continue to ignore the error message.

Imagine data_log takes in not one but a few more arguments, and the inner logic of it gets more complex. You decide to manually rename the_list to array_object , but leaves a few miss here and there.

If you run the code again, it might just work, but the results will certainly be strange. That is because now the_list refers to the global object, array_object refers to the local one, they are different and you mixed them back and forth inside your function.

Avoid “Shadows name from outer scope”

Now that we know the reason behind the warning, the solution is quite simple : You need to avoid reusing names in your code.

Doing so will not only reduce weird behaviour in your code, but also make debugging easier, since you would end up with NameError if Python cannot find a global name or local name.

One more thing to remember is that you should not “shadow” modules, classes and functions the same way you shadow names, too.

This is how our example will look like if it doesn’t shadow names :

the_list = [1, 2, 3] def data_log(a_list): # Warning: "Shadows 'the_list' from outer scope print(a_list) data_log(the_list)

Or you can just move the global variables to another function like so :

def data_log(a_list): print(a_list) def main(): the_list = [1, 2, 3] data_log(the_list)

We’ve also covered how to fix locale.Error: unsupported locale setting once and for all, which might be a good read for new Python developers. We hope this article will help you solve your problem and write better, cleaner, error-free code.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *