On 23May2021 21:02, Stestagg <stest...@gmail.com> wrote: >On Sun, 23 May 2021 at 20:37, hw <h...@adminart.net> wrote: >> I don't know about shadowing. > >Shadowing is effectively saying “within this bit of code, (scope) I’m going >to use an already-used name for my own value”
An example might make this clearer: x = 1 # global variable def f(a): x = a * 2 return x Inside the function f() the name 'x" shadows the global "x"; references to "x" are to the function's local vairable. Which is very desireable. >If I have defeated a whole variable type >> by naming a variable like a variable type, I would think it is a bad >> idea for python to allow this without warning. > >There are some reasons why allowing this is quite nice. And there’s >actually a ton of corner cases to consider when thinking about changing the >rules As Stestagg has mentioned, there are also tools called linters which warn you about issues like this. Tools like pyflakes, pylint, pycodestyle all inspect your code for a wide variety of potential errors and discouraged habits. Not to mention tools like mypy which do type validation. >Interestingly python 3 made this a little bit better by stopping you from >rebinding (shadowing) a number of built ins, such as True and False. > >In your case, I agree that it is super confusing. One thing to learn to >look out for is if you assign to a name, then use that name on a different >context, expecting it to be different, then that’s not likely to work as >you expect. > >It seems like a recipie >> for creating chaos. The runtime lets you do all sorts of things. Linters and type checkers exist to help you notice if you're writing such a recipe. There _are_ times when it is useful to shadow a builtin name. Not being able to prevents a useful activity. A common example in my own code is this: from cs.upd import Upd, print which shadows the print() builtin. The Upd class maintains status lines such as progress bars and so forth. It provides a print() function which withdraws the status lines, runs the builtin print, then restores them, allowing normal idiomatic use of print() in scripts making use of the status lines. Similar situations abound. Cheers, Cameron Simpson <c...@cskk.id.au> -- https://mail.python.org/mailman/listinfo/python-list