- Как правильно именовать переменную, чтобы избежать предупреждения типа «Имя тени из внешней области видимости» в Python
- 3 ответа
- tslint error Shadowed name: ‘Observable’
- 3 Answers 3
- tslint Error — Shadowed name: ‘err’
- 5 Answers 5
- Вопросы по kotlin
- 2 вопрос:
- вопрос про typealias
- как импортировать функции из android.* в standalone .kt?
- disallow variable declarations from shadowing variables declared in the outer scope (no-shadow)
- Rule Details
- Options
- builtinGlobals
- hoist
- hoist: functions
- hoist: all
- hoist: never
- allow
Как правильно именовать переменную, чтобы избежать предупреждения типа «Имя тени из внешней области видимости» в 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 («Настройки» -> «Редактор» -> «Стиль кода» -> «Проверки» -> скрытие имен из внешних областей). Но обычно это плохая идея.
Источник
tslint error Shadowed name: ‘Observable’
I am getting the following error when running tslint that I wasn’t getting before..
I followed this tutorial for adding a debug operator to Observable and it is working fine except I am getting this lint error. I had been using this debug operator for a while without getting the lint error and I’m not sure why I am getting it now.
Here is the code at line 27 to amend the type definition with the debug method
Does anyone know how I can clear this lint error? Thank you!
3 Answers 3
Here is a quick example of variable shadowing, to make the warning clear.
If you are declaring an extension to an interface (i.e. both instances of Observable have the same common root) you are not technically shadowing, but if you have an Observable at multiple levels, it may make it unclear to which you are referring.
You can switch off shadowing warnings using the option:
Is interface shadowing a problem in TypeScript?
Not really — you would catch a situation where an interface was declared inside a function, which you would also catch because if it was a problem the TypeScript compiler would already be telling you there is a problem. i.e. the member list would show you the correct members in both scopes.
Interfaces are also erased — so there is no post-compile confusion, for example if someone were to use your TypeScript library in a JavaScript program.
I’m happy to change my opinion if someone can supply a realistic example of where interface shadowing would cause a problem.
Источник
tslint Error — Shadowed name: ‘err’
tslint is currently throwing the following error
Here is the code
Anybody have a clue on what the best way would be to solve this and what the error even means?
5 Answers 5
You are using the same variable «err» in both outer and inner callbacks, which is prevented by tslint.
If you want to use the same variable then «no-shadowed-variable»: false, otherwise do as below.
Add this comment just above the error line—
// tslint:disable-next-line:no-shadowed-variable
This shadowed name tslint error is due to repetition of the name ‘err’ twice in your callback functions. You can change either anyone ‘err’ to other name so this should work.
Example: This should work
When same variable is declared multiple times in same scope, this warning occurs.
Use different variable names in such cases.
this line will disable your error,
but it’s not okay to have tow err variables you can also change the second err variable name to something different
I had an error like this interfaces.ts:119:26 — Shadowed name: ‘POST’
I have disabled this error case with this line // tslint:disable: no-shadowed-variable because sometimes typescript compiler cannot understand your code right 🙂
Источник
Вопросы по kotlin
Если умное приведение вам не нужно, то используйте запись с безопасным оператором ?.
Функция будет вызвана только в том случае, если значение a отлично от null. Безопасные вызовы можно сцеплять.
2 вопрос:
пытаюсь создать пакет. Не получается
Функция toString будет вызвана только если значение отлично от null. Ведь именно она идёт после безопасного оператора, а не print. Если бы toString всё-таки был вызван, то тут выскочил бы NPN.
Метод toString не вызывается, т. к. он определён для Any. А тут String? и будет вызываться вот этот extension https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/to-string.html
Т. к. у тебя Int?, а не Int, то вызывается не метод toString, а extension https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/to-string.html
Вместо println(«$a» + » » + «$b») можно просто записать println(«$a $b»)
P.S.: пишу по памяти.
если сделать не null
нужно было указать при компиляции файл kitten.kt. Вопрос решен
Ну раз уж тут набрасывают… не могу сказать что то, что я вижу выглядит лучше руста.
вопрос про typealias
А вот с функцией это не получается сделать
Как это правильно реализовать?
как импортировать функции из android.* в standalone .kt?
‘a?.toString()’ означает, что функция ‘toString’ не будет вызвана и исключения по nullptr не будет
в свою очередь ‘print’ может принимать null строку, значит код корректен и выведет ‘null’
если не хочется вызывать функцию, то пишем
это означает, что let будет вызван только если ‘a’ не null, а в теле функции мы печатаем строку ‘it’, которая передана параметром в ‘let’.
Источник
disallow variable declarations from shadowing variables declared in the outer scope (no-shadow)
Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example:
In this case, the variable a inside of b() is shadowing the variable a in the global scope. This can cause confusion while reading the code and it’s impossible to access the global variable.
Rule Details
This rule aims to eliminate shadowed variable declarations.
Examples of incorrect code for this rule:
Options
This rule takes one option, an object, with properties «builtinGlobals» , «hoist» and «allow» .
builtinGlobals
The builtinGlobals option is false by default. If it is true , the rule prevents shadowing of built-in global variables: Object , Array , Number , and so on.
Examples of incorrect code for the < "builtinGlobals": true >option:
hoist
The hoist option has three settings:
- functions (by default) — reports shadowing before the outer functions are defined.
- all — reports all shadowing before the outer variables/functions are defined.
- never — never report shadowing before the outer variables/functions are defined.
hoist: functions
Examples of incorrect code for the default < "hoist": "functions" >option:
Although let b in the if statement is before the function declaration in the outer scope, it is incorrect.
Examples of correct code for the default < "hoist": "functions" >option:
Because let a in the if statement is before the variable declaration in the outer scope, it is correct.
hoist: all
Examples of incorrect code for the < "hoist": "all" >option:
hoist: never
Examples of correct code for the < "hoist": "never" >option:
Because let a and let b in the if statement are before the declarations in the outer scope, they are correct.
allow
The allow option is an array of identifier names for which shadowing is allowed. For example, «resolve» , «reject» , «done» , «cb» .
Examples of correct code for the < "allow": ["done"] >option:
Источник