Variable scoping rules in Python?
MRAB
google at mrabarnett.plus.com
Mon Oct 8 18:46:56 EDT 2007
On Oct 8, 4:06 pm, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> joshua.dav... at travelocity.com a écrit :
>
> > Ok, I'm relatively new to Python (coming from C, C++ and Java). I'm
> > working on a program that outputs text that may be arbitrarily long,
> > but should still line up, so I want to split the output on a specific
> > column boundary.
>
> FWIW :http://docs.python.org/lib/module-textwrap.html
>
>
>
>
>
> > Since I might want to change the length of a column,
> > I tried defining the column as a constant (what I would have made a
> > "#define" in C, or a "static final" in Java). I defined this at the
> > top level (not within a def), and I reference it inside a function.
> > Like this:
>
> > COLUMNS = 80
>
> > def doSomethindAndOutputIt( ):
> > ...
> > for i in range( 0, ( len( output[0] ) / COLUMNS ) ):
> > print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ]
> > print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ]
> > ..
>
> > etc. etc. It works fine, and splits the output on the 80-column
> > boundary just like I want.
>
> > Well, I decided that I wanted "COLUMNS = 0" to be a special "don't
> > split anywhere" value, so I changed it to look like this:
>
> > COLUMNS = 80
>
> > def doSomethindAndOutputIt( ):
> > ...
> > if COLUMNS == 0:
> > COLUMNS = len( output[ 0 ] )
>
> > for i in range( 0, ( len( output[0] ) / COLUMNS ) ):
> > print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ]
> > print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ]
> > ..
>
> Since you don't want to modify a global (and even worse, a CONSTANT),
> the following code may be a bit cleaner:
>
> def doSomethindAndOutputIt( ):
> ...
> if COLUMNS == 0:
> columns = len( output[ 0 ] )
> else:
> columns = COLUMNS
> for i in range( 0, ( len( output[0] ) / COLUMNS ) ):
> print output[0][ i * columns : i * columns + ( columns - 1 ) ]
> ..
>
[snip]
range() can accept 3 arguments (start, stop and step) so you could
write:
for i in range( 0, len( output[0] ), columns ):
print output[0][ i : i + columns ]
..
More information about the Python-list
mailing list