[Tutor] scoping oddity

ZIYAD A. M. AL-BATLY zamb at saudi.net.sa
Sat May 7 21:41:57 CEST 2005


On Sat, 2005-05-07 at 12:56 -0400, Michael wrote:
> Tanja, Bob, Brian,
> 
> Many thanks for your help.  
> 
> And perhaps the way in which I posed the question was misleading.  In a
> process I am writing, I was actually trying not to use global variables, as
> I agree with Brian.  However, I inadvertantly used a variable within a 'def'
> block that I had used outside of that 'def' block and got 'bitten'.  It was
> in tracking my bug down that I became a tad confused.  
> 
> Actually, now that I know the answer, it all seems so obvious.  At least
> until I get bitten by it again!  D'OH!
> 
> Michael
> ...snip...

(I wonder why nobody mentioned this method?!!)

If you want to use a new variable with the same name as a global one use
default argument (credits goes to the authors of O'REILLY's Learning
Python):

        x = 5
        
        def testa(astr):
             print astr, x
        
        testa(22)
        
        def testb(astr, x = x):
             x = x - 1
             print astr, x
        
        testb(22)
        
        def testc(astr):
             print astr, x-1
        
        testc(22)

(By the way, this is my first post to PyTutor!)
(Michael, sorry for this duplicate message(s).  I didn't realize I
replayed to *only* you until now.)
Ziyad.



More information about the Tutor mailing list