0

From python reference manual:

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.

and

When a name is used in a code block, it is resolved using the nearest enclosing scope.

So it is not obviously from this quotes what scope does mean. Is it true that scope is a collection of bindings name-->value? And what does mean enclosing scope? Does it mean that every scope must contain a reference to the enclosing scope?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • That first sentence defines what *scope* *is*. – Martijn Pieters Feb 26 '14 at 13:18
  • *scope* is the extend a name is visible. Within a function, local names are all visible; you are within a single scope. – Martijn Pieters Feb 26 '14 at 13:20
  • @Martijn Pieters Is scope an object in python? –  Feb 26 '14 at 13:21
  • Note the difference between 'a local variable is *defined*' and 'when a name is *used*'; the difference is crucial. – Martijn Pieters Feb 26 '14 at 13:21
  • No, scope is a *concept*. An abstract idea. Not a concrete object. – Martijn Pieters Feb 26 '14 at 13:21
  • @Martijn Pieters And what about enclosing scope? Is it defined an including relation between scopes? –  Feb 26 '14 at 13:24
  • 2
    The documentation there defines that any name defined in a block in a function, is visible in all blocks in a function. Because functions are defined in a module, and a module is also a scope, there is an implied hierarchy here. There are scopes nested in scopes (functions in modules), and these can be nested further (functions in functions in modules). `class` blocks also form scopes, and the rules that govern these are special (*The scope of names defined in a class block is limited to the class block*). – Martijn Pieters Feb 26 '14 at 13:31

1 Answers1

0

@Martjin Pieters clarifications and answers are awesome, but I'd like to add that beyond python, scope is a computer science/programming concept that spans across basically all programming languages currently in use.

To learn more about what scope is, generally, aside from in python, I'd start here: http://en.wikipedia.org/wiki/Scope_(computer_science)

Many languages, including python, follow the same set of basic scoping rules, but the details can be different between languages. Thus, if you're really asking "what is scope?" then starting at a general source may be more useful than learning the intricacies of python's scoping (at least at first).

Joan Smith
  • 931
  • 6
  • 15
  • In the ECMA-262 spec visibilty defines pretty formally as an execution context and a lexical environment. I'm expected to find the same construction in the python... –  Feb 26 '14 at 16:06