Can module access global from __main__?

Tony Nelson *firstname*nlsnews at georgea*lastname*.com
Sat Oct 15 01:55:10 EDT 2005


In article <1129091588.810070.165280 at g14g2000cwa.googlegroups.com>,
 "Neal  Norwitz" <nnorwitz at gmail.com> wrote:

> Steve Holden wrote:
> > Neal Becker wrote:
> > >
> > > Still curious about the answer.  If I know that I am imported from 
> > > __main__,
> > > then I can do access X as sys.modules[__main__].X.  In general, I don't
> > > know how to determine who is importing me.
> > >
> > I don't think you can without huge amounts of introspection - it's even
> > worse than the "what's the name of this object" question that seems to
> > come up regularly.
> 
> import sys
> 
> frame = sys._getframe()
> caller = frame.f_back
> print 'Called from', caller.f_code.co_filename, caller.f_lineno
> # for more info, look into the traceback module
> 
> > A module can be imported from multiple modules, and
> > you only get to execute code on the first import.
> > Even then (on the first import) I am not sure how you could introspect
> > to find the answer you want.
> 
> You can install your own __import__() hook to catch all imports.
> 
> Just because you can do something, it doesn't follow that you should do
> it, especially in this case.  Unless you really, really need these
> tricks, they shouldn't be used.

Neal, I have a similar question (in that maybe I shouldn't do 
something), and you seem to know your way around modules, so I'll just 
butt in.  If this isn't OK I'll post as a new thread.

I have written a python module that uses some C functions.  I wrote the 
module in two parts, one python, one pyrex (C).  They need to share some 
globals.  (I use pyrex to handle ref counting.  I think I'm glad I did.)

At first they just sort of mutually imported each other, and it worked 
until I put tests in the python one and set it up to run them when it 
was __main__.  This reminded me that there are also other ways modules 
can be imported under different names, so I tried a different approach.

Now I'm just shoving references to the python module's globals into the 
pyrex module (first defining them in the pyrex module).  The pyrex 
module doesn't import the python module anymore.  This also works, even 
when the python module has a different name ("__main__").  I just feel 
dirty about it.

How does one normally make a module that uses some functions in C?  Will 
that approach work with pyrex?  With globals?
________________________________________________________________________
TonyN.:'                        *firstname*nlsnews at georgea*lastname*.com
      '                                  <http://www.georgeanelson.com/>



More information about the Python-list mailing list