Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6697

Re: scope of function parameters (take two)

References <F8395F78-615E-4FBD-B6FC-1D6173EAEA45@mcgill.ca> <F4EAD1ED-563D-4D6E-A50C-68308A9F26B7@mcgill.ca>
Date 2011-05-31 13:05 +1000
Subject Re: scope of function parameters (take two)
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2291.1306811129.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, May 31, 2011 at 10:28 AM, Henry Olders <henry.olders@mcgill.ca> wrote:
> I don't believe I'm the only person who thinks this way. Here is a quote from wikipedia: "It is considered good programming practice to make the scope of variables as narrow as feasible so that different parts of a program do not accidentally interact with each other by modifying each other's variables. Doing so also prevents action at a distance. Common techniques for doing so are to have different sections of a program use different namespaces, or to make individual variables "private" through either dynamic variable scoping or lexical variable scoping." (http://en.wikipedia.org/wiki/Variable_(programming)#Scope_and_extent).
>

Side point, on variable scope.

There is a philosophical split between declaring variables and not
declaring them. Python is in the latter camp; you are not required to
put "int a; char *b; float c[4];" before you use the integer, string,
and list/array variables a, b, and c. This simplifies code
significantly, but forces the language to have an unambiguous scoping
that doesn't care where you assign to a variable.

Example:

def f():
  x=1  # x is function-scope
  if cond: # cond is global
    x=2 # Same function-scope x as above
  print(x) # Function-scope, will be 2 if cond is true

This is fine, and is going to be what you want. Another example:

def f():
  print(x) # global
  # .... way down, big function, you've forgotten what you're doing
        for x in list_of_x:
          x.frob()

By using x as a loop index, you've suddenly made it take function
scope, which stops it from referencing the global. Granted, you
shouldn't be using globals with names like 'x', but it's not hard to
have duplication of variable names. As a C programmer, I'm accustomed
to being able to declare a variable in an inner block and have that
variable cease to exist once execution leaves that block; but that
works ONLY if you declare the variables where you want them.

Infinitely-nested scoping is simply one of the casualties of a
non-declarative language.

Chris Angelico

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: scope of function parameters (take two) Chris Angelico <rosuav@gmail.com> - 2011-05-31 13:05 +1000

csiph-web