scoping questions

Shalabh Chaturvedi shalabh at cafepy.com
Thu Jun 3 04:36:36 CEST 2004


David Stockwell wrote:


> Hi,
> 
> Another of my crazy questions.  I'm just in the process of learning so 
> bear with me if you can.   I actually ran it....  with two test cases
> 
> TEST CASE 1:
> Say I have the following defined:
> --- beginning of code snippet ----
> 
> def me(aFile):
>   """
>     Note I am testing scoping
>   """
>   aFile = 'hello world'
>   print aFile
> 
> 
> 
> aFile = open('/tmp/test','r')
> me(aFile)
> data = aFile.read()
> print data
> 
> ------ end of code snippet ----
> my test file has a sentence 'This is a test of the /tmp/test file'
> 
> When I run it I observed this output:
> hello world
> This is a test of the /tmp/test file
> 
[snipped op's understanding of above]

> 
> TEST CASE 2:
> -------
> def me(aFile):
>   """
>     Note I am testing scoping
>   """
>   aFile = 'hello world'
>   print aFile
> 
> 
> def me2(dog):
>   """
>     Note I am testing scoping
>   """
>   print "Inside me2"
>   dog.close()
> 
> 
> aFile = open('/tmp/test','r')
> me(aFile)
> data = aFile.read()
> print "test1", data
> aFile.close()
> aFile = open('/tmp/test','r')
> 
> me2(aFile)
> print "test2", aFile.read()
> =====
> 
> It bombs out on the last line because aFile was closed in the function 
> 'me2'.
> 
> Perhaps the way to explain it is that Inside me2 when my copy of the 
> original reference is made, I have a global and local variable both 
> referencing the same 'object'.   I am able to do operations in the local 
> me2 scope and have them effect the behavior of the global scope.
> 
> Its just a bit confusing because python is apparently smart enough to 
> realize that my action on the local reference hasn't redefined the 
> capability of the global so it has allowed this to occur on the actual 
> global file referenced object. (as opposed to just a local copy).  And I 
> didn't return anything....
> 
> 
> I'm just confused a bit here.... Perhaps someone can clarify
> 
> Thanks

I'd like to point out the different operators used in the two cases: 
equal-to (=) vs dot (.). These two work very differently.

Equal-to binds a 'name' to an object. A = B will bind the name A to the 
object currently bound to name B. B remains bound to the same object. If 
the name A was already bound, it doesn't matter, it will now be bound to 
the new object.

Dot accesses an attribute on an object. A.f() will call the method f() 
of object A. The method may or may not change the object itself. Some 
objects cannot be changed (they are immutable eg. tuples and strings).

HTH,
Shalabh





More information about the Python-list mailing list