Variable scoping rules in Python?

Paul Hankin paul.hankin at gmail.com
Mon Oct 8 14:13:34 EDT 2007


On Oct 8, 3:17 pm, joshua.dav... at travelocity.com wrote:
> 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.  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( ):
>   ...
>   if COLUMNS == 0:
>     COLUMNS = len( output[ 0 ] )

Often it's better to make your global 'constant' an optional argument,
especially if certain values have special meanings to your function.

def doSomethingAndOutputIt(columns = 80):
    ...
    columns = columns or len(output[0])

--
Paul Hankin




More information about the Python-list mailing list