python / cpython

The Python programming language
https://www.python.org
Other
62.47k stars 29.99k forks source link

Add a note about variable scope inside a block when compared to other languages. #110731

Open varun-masuraha opened 11 months ago

varun-masuraha commented 11 months ago

Unlike many other languages, blocks in Python do not create a new scope. For instance, variables defined in loops or if statements are available outside of those blocks. I could not find this information in documentation. Should this be mentioned somewhere, either as a separate topic or perhaps in chapter 9.2 of The Python Tutorial ? I think it would be useful for people with prior programming experience.

Link to the same thread on discussion board: https://discuss.python.org/t/documentation-about-scope-inside-loops-when-compared-to-c-c/30739

jtranquilli commented 11 months ago

As Karl Knechtel responded on that thread: ''' A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace. Although scopes are determined statically, they are used dynamically. At any time during execution, there are 3 or 4 nested scopes whose namespaces are directly accessible:

the innermost scope, which is searched first, contains the local names the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contain non-local, but also non-global names the next-to-last scope contains the current module’s global names the outermost scope (searched last) is the namespace containing built-in names ''' is an excerpt from the chapter on classes I believe. Totally possible that scope deserves it's own chapter but information on how scope works in Python is available in the docs.

varun-masuraha commented 11 months ago

Yes, new programmers won't have any diffculty and the existing doc seems good enough, but for someone like me with many years of experience on other languages, it was little debugging required to realize this dissimiliarity on python. Or perhaps it's just me 🙂