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

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

  • автор:

Как правильно именовать переменную, чтобы избежать предупреждения типа «Имя тени из внешней области видимости» в Python

Я использую PyCharm для своей программы на Python, и я написал коды ниже:

Поэтому я получаю текст предупреждения типа «Shadows name ‘ds’ from external scope». Я знаю влияние области действия, но я все еще хочу использовать тот же формат кода, что и «для root, ds, fs in . » во внутренней или внешней области видимости.

Я искал PEP8, однако до сих пор не знаю, как назвать переменную в функции нормативно.

Не могли бы вы дать мне предложение?

3 ответа

В общем: просто проигнорируйте предупреждение. Это просто предупреждение, а не ошибка. Вы можете использовать как глобальные, так и локальные имена, которые совпадают.

Однако я бы не стал вызывать os.walk() вызов в глобальной области видимости в любом случае . Я бы предпочел поместить это и в функцию, которая имеет счастливый побочный эффект от имен, которые вы использовали, больше не глобальные.

Например, вы можете использовать функцию main() :

Вообще говоря, вы не хотите оставлять имена циклов, такие как root, ds, fs , как глобальные переменные в вашем модуле. Это детали реализации, и они не должны становиться частью общедоступного API модуля. Если у вас есть для использования цикла for , подобного этому, в глобальной области, используйте _ префиксы с одним подчеркиванием в именах и рассмотрите возможность их удаления после цикла с <> :

Если ваши имена повторяются, используйте «_», чтобы избежать таких предупреждений. Это обычная практика.

Это предупреждение shadows name XX from outer scope — это не проблема PEP8, а реальное предупреждение от Pycharm о том, что повторное использование имен переменных таким образом — плохая идея. Другими словами, это не проблема стиля кода, а то, что может привести к проблемам в более поздних программах.

Мое предложение было бы, ну, во всяком случае, избегать повторного использования имен переменных, когда это возможно. Набрав это:

for root_path, directory_name, file_name in os.walk(root_dir):

Не займет много времени и позволит избежать нежелательных побочных эффектов в будущем.

Тем не менее, если по какой-либо причине вам абсолютно необходимо повторно использовать имена переменных и вы хотите избавиться от предупреждающего сообщения, вы можете отключить его в Pycharm («Настройки» -> «Редактор» -> «Стиль кода» -> «Проверки» -> скрытие имен из внешних областей). Но обычно это плохая идея.

What Is Shadows Built In Name? With Code Examples

Hello everyone, in this post we will examine how to solve the What Is Shadows Built In Name? programming puzzle.

As we have seen, the What Is Shadows Built In Name? problem was solved by using a number of different instances.

What does shadows built in name mean in Python?

“What is shadows built in name?” Code Answer # You started a variable with the name that was used in the standard library. Now that library object is not available to you.

What does shadows name from outer scope?

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.01-Mar-2021

What is shadow in Python?

The shadow() function is an inbuilt function in the Python Wand ImageMagick library which is used to generates an image shadow. Syntax: shadow(alpha, sigma, x, y) Parameters: This function accepts four parameters as mentioned above and defined below: alpha: This parameter stores the ratio of the transparency.22-Aug-2021

What does outer scope mean?

Scopes of any type (code block, function, module) can be nested. The scope contained within another scope is named inner scope. In the example, if code block scope is an inner scope of run() function scope. The scope that wraps another scope is named outer scope.20-Apr-2020

What is shadowed name typescript?

Shadowing means declaring an identifier that has already been declared in an outer scope. Since this is a linter error, it's not incorrect per se, but it might lead to confusion, as well as make the outer i unavailable inside the loop (where it is being shadowed by the loop variable.)24-Sept-2017

What is shadow C#?

C# also provides a concept to hide the methods of the base class from derived class, this concept is known as Method Hiding. It is also known as Method Shadowing. In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword.19-Mar-2019

What is shadowing rust?

Shadowing in Rust Shadowing is such a simple language feature. However, it has a significant effect on the code you write daily. Shadowing allows you to re-declare a variable in the same scope, using the same name. The re-declared variable differs from the original by having a different type.07-Sept-2021

What is variable shadowing C++?

So what happens when we have a variable inside a nested block that has the same name as a variable in an outer block? When this happens, the nested variable “hides” the outer variable in areas where they are both in scope. This is called name hiding or shadowing.03-Jan-2020

What is data shadowing in Java?

Shadowing in Java is the practice of using variables in overlapping scopes with the same name where the variable in low-level scope overrides the variable of high-level scope. Here the variable at high-level scope is shadowed by the low-level scope variable.30-Aug-2021

What is a shadow assignment?

It involves working with another employee who might have a different job in hand, have something to teach, or be able to help the person shadowing him or her to learn new aspects related to the job, organization, certain behaviors or competencies. Organizations have been using this as an effective tool for learning.

What is the problem with shadowing names defined in outer scopes?

I just switched to PyCharm and I am very happy about all the warnings and hints it provides me to improve my code. Except for this one which I don’t understand:

This inspection detects shadowing names defined in outer scopes.

I know it is bad practice to access variable from the outer scope, but what is the problem with shadowing the outer scope?

Here is one example, where PyCharm gives me the warning message:

TylerH's user avatar

11 Answers 11

There isn’t any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda , but miss one of the places it is used in the function’s body. Now data refers to the global, and you start having weird behaviour — where you would have a much more obvious NameError if you didn’t have a global name data .

Also remember that in Python everything is an object (including modules, classes and functions), so there’s no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it — bad luck — foo .

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

Peter Mortensen's user avatar

It doesn’t matter how long your function is, or how you name your variable descriptively (to hopefully minimize the chance of potential name collision).

The fact that your function’s local variable or its parameter happens to share a name in the global scope is completely irrelevant. And in fact, no matter how carefully you choose you local variable name, your function can never foresee "whether my cool name yadda will also be used as a global variable in future?". The solution? Simply don’t worry about that! The correct mindset is to design your function to consume input from and only from its parameters in signature. That way you don’t need to care what is (or will be) in global scope, and then shadowing becomes not an issue at all.

In other words, the shadowing problem only matters when your function need to use the same name local variable and the global variable. But you should avoid such design in the first place. The OP’s code does not really have such design problem. It is just that PyCharm is not smart enough and it gives out a warning just in case. So, just to make PyCharm happy, and also make our code clean, see this solution quoting from silyevsk’s answer to remove the global variable completely.

This is the proper way to "solve" this problem, by fixing/removing your global thing, not adjusting your current local function.

2, Pycharm variable name (Shadows Built-in Name ‘ID ")

Pycharm prompt instance attribute users_index defined outside __INIT__

Problem Description:

Pycharm prompt instance attribute users_index defined outside __INIT__

Self.users_index = 0 # will appear underscore prompt instance attribute users_index defined outside __init__

Self.groups_index = 0 # will appear underscore prompt instance attribute groups_index defined outside __init__

Cause Analysis:

Instance attribute attribute_name defines exogenous __init

The idea behind this prompt is to readability. We hope to find all the properties that the instance may have by reading its __ init __ method. Things doing values ​​outside the construction method will reduce the testability of the code.

Split is initialized to other methods. In this case, you can simply assign attributes to no sub-initialization methods in __ init __.

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

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