Name resolution (programming languages): Difference between revisions

Content deleted Content added
Name masking: Disambiguated and clarified the code example greatly.
Static versus dynamic: Greatly clarified and simplified the Python example, updated the source for accuracy and timelieness.
Line 19:
Static name resolution catches, at compile time, use of variables that are not in scope; preventing programmer errors. Languages with dynamic scope resolution sacrifice this safety for more flexibility; they can typically set and get variables in the same scope at runtime.
 
For example, in the [[Python (programming language)|Python]] interactive [[REPL]]:
<source lang="pycon">
>>> number = 999
>>> locals()['num'] = 999 # equivalent to: num = 999
>>> nounfirst_noun = "troubles"
>>> noun2second_noun = "hound"
>>> # which variables to use are decided at runtime
>>> print(f"{numnumber} {nounfirst_noun} and a {noun2second_noun} ain't one".format(**locals()))
999 troubles and a hound ain't one
 
</source>
However, relying on dynamic name resolution in code is discouraged by the Python community.<ref>{{cite web|url=http://mail.python.org/pipermail/python-ideas/2009-May/004582.html|title=<nowiki>[</nowiki>Python-Ideas<nowiki>]</nowiki> str.format utility function|date=9 May 2009|accessdate=2011-01-23}}</ref><ref>{{cite web|url=http://diveintopython.org/html_processing/dictionary_based_string_formatting.html|title=8.6. Dictionary-based string formatting|work=diveintopython.org|publisher=Mark Pilgrim|accessdate=2011-01-23}}</ref> The feature also may be removed in a later version of Python.<ref>{{cite web |url=https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces|title=9. Classes - Python v2.7.1 documentation |quote=It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.)|accessdate=20112019-0107-2324}}</ref>
 
Examples of languages that use static name resolution include [[C (programming language)|C]], [[C++]], [[E (programming language)|E]], [[Erlang (programming language)|Erlang]], [[Haskell (programming language)|Haskell]], [[Java (programming language)|Java]], [[Pascal (programming language)|Pascal]], [[Scheme (programming language)|Scheme]], and [[Smalltalk]]. Examples of languages that use dynamic name resolution include some [[Lisp (programming language)|Lisp]] dialects, [[Perl]], [[PHP]], [[Python (programming language)|Python]], [[REBOL]], and [[Tcl]].