Scope questions

Dale Strickland-Clark dale at out-think.NOSPAM.co.uk
Sun Jul 23 10:11:12 EDT 2000


Vary handy. Thanks

Dale Strickland-Clark


"Eric Jacobs" <none at none> wrote in message
news:snhoclpb6tt61 at corp.supernews.com...
> In article <8l7vgk$73t$1 at supernews.com>, "Dale Strickland-Clark"
> <dale at out-think.NOSPAM.co.uk> wrote:
> > Could someone help me out with some scope and instantiation questions?
> >
> > In moduleA we have:
> >
> > varB = 1
> > class classC:
> >     varD = 1
> >     def __init__(self):
> >         self.varE = 1
> >
> > As I understand it, varB appears when the module is imported and stays
> > around until the end of the program.
>
> It appears when the statement "varB = 1" is executed, which would be
> at import time since the statement is not in a def.
>
> The name varB will persist until it is deleted or the module is deleted
> (which will delete the namespace dictionary it is in.)
>
> >
> > When does varD appear? How long does it exist?
>
> When the statement "varD = 1" is executed. A class definition doesn't
> change the flow of execution. Since the statement is not in a def, it
> also gets created at import time.
>
> try...
>       class z:
>           print "hello world"
>
> It exists until it is deleted or the class is deleted (again, deleting
> the namespace dictionary.)
>
> >
> > In the main code I use the above module and have:
> >
> > import moduleA
> > varJ = moduleA.classC
> > varK = varJ.varE
> > varJ = None
> >
> > Again, as I understand it, varK contains a reference to varE in class
> > instance varJ.
>
> No, it does not contain a reference to varE. There is no built-in way
> to reference names in Python. Rather, it is assigned a reference to
> whatever object varE is referencing. (You didn't provide any code which
> would create a name varE in classC, so this probably won't work.
> self.varE refers to a varE in an instance of classC.)
>
> > What happens to varK when the instance reference in varJ
> > goes away?
>
> varJ is not an instance reference. It is a reference to classC. varK
> will continue to reference the object that varE was referencing even
> if the name varE is nowhere to be found.
>
> > Does the instance get deleted or is there still a reference
> > to it?
>
> There are no instances here, but classC will not be deallocated because
> it is still referenced in moduleA's namespace.
>
>
> If you had done:
>
>    funcK = lambda varJ=varJ: varJ.varE
>
> then the expression funcK() would be a sort of a "reference" to the
> name varE. In this case, varJ would have its reference count
> incremented because it is being referenced in funcK's default
> argument list, and so it wouldn't be deleted before funcK itself
> is deleted.
>
> Hope this answers your question.
>
>





More information about the Python-list mailing list