[Tutor] how to make an lexical scope block?

Alan Gauld alan.gauld at yahoo.co.uk
Sat Aug 5 08:22:48 EDT 2017


On 05/08/17 08:23, Xiaosong Chen wrote:
> In C, it's a common pattern to use temporary variables in an lexical
> scope to prevent the global scope from getting dirty.

This was very common in the early days of C - around 1979-1985 - when
compilers often only considered the first 4 (or 6) characters of a
variable name - even though the name itself could be 16 or 32
characters long.

Thus 'index' and 'indeterminate' and 'indent' were all seen
as the same name. This required careful limiting of the lexical
scope of variables. Nowadays I don't see that as an issue and
most of the C code I work with doesn't limit scope beyond
a function definition. Maybe some old school C programmers
still worry about tight scoping but not the ones I work with!

As for Python it limits names to global (actually module)
and function scope. If you are creating well structured
code based on short clear functions there should not be
much of a problem.

So, to answer the question,

1) we don't tend to need such scoping because the language
permits many names, and it provides module and function scopes.

2) Also we avoid importing with the

from foo import *

style which increases risks of name pollution.

3) We need fewer temporary variables because we can use
tuple unpacking and generator expressions to replace many
scenarios where C would use a temporary variable.

In practice I've never found it to be an issue.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list