[Tutor] Objects, persistence & getting

Kent Johnson kent37 at tds.net
Sun Jan 16 23:40:34 CET 2005


I'm not sure I understand your question. but if I do, the answer is, sometimes you can do it, but it 
is rarely a good idea.

Liam Clarke wrote:
> If I understand correctly, once an object is created, as long as
> references to it exist, it isn't garbage collected.

That's right.

> 
> So, if module a.py creates an instance of class foo, can method bar in
> module b.py access foo without foo being passed directly to bar?

I think you mean, can bar access the instance of foo created in a.py?

Probably you can access it. Probably it's not a good idea.

Somehow you need to access the reference to a foo that is being kept in a.py. If a.py looks like this:
# a.py
class foo:
   pass

a_foo = foo()

then a_foo is a module-level variable and it is accessible from other modules as a.a_foo:

# b.py
import a

def bar():
   print a.a_foo

On the other hand, the foo instance might have been created as a local variable in some function 
that (calls a function that) calls bar(). To access this instance of foo you need to dig around in 
the stack frames and you would need some information about where the foo was created. This is in 
general a bad idea...

For some examples of how to play with stack frames, search for sys._getframe() in the Python 
cookbook or in comp.lang.python. The contents of a stack frame are documented in the Language 
Reference section 3.2.

> 
> Does that make sense? So, foo is floating around in the namespace, and
> bar just wants to grab a field of foo. Can it? I had a poke around the
> namespace yesterday, and got lost in hordes of methods that look like
> __this__, which is ugly.

Although this is probably possible, there aren't very many good reasons for doing it. It's better to 
just pass a reference to the object to the functions that need it.

Kent

> 
> Regards,
> 
> Liam Clarke



More information about the Tutor mailing list