How do I access a main frunction from an import module?

John Machin sjmachin at lexicon.net
Fri Nov 24 12:43:28 EST 2006


Jim wrote:
> Hi,
>
> I have created an import module.  And would like to access a function
> from the main script, e.g.,
>
> file abc.py:
> ###################
> def a():
>     m()
>     return None
> ####################
>
> file main.py:
> #####################
> from abc import *
> def m():
>     print 'something'
>     return None
>
> a()
> ######################
>
> python25.exe main.py
>

Although there are literally correct answers to your question, the best
answer is "Don't do that. You would be creating circular references
between modules, and run the risk of emulating the mythical ooloo bird
by disappearing up your own fundamental orifice". Some possible
practical solutions:

1. Put the m function in a 3rd file/module. Then any other module which
needs it can import/call.

2. If you think that's not a good idea, then put it in abc.py (it's not
used in main.py in your example).

3. Maybe this will suit what you are really trying to do:

 file abc.py:
 ###################
 def a(argfunc): # <<<<<=====
     argfunc() # <<<<<=====
 ####################

 file main.py:
 #####################
 from abc import *
 def m():
     print 'something'

 a(m) # <<<<<=====
 ######################

4. If you think *that's* not a good idea, then you might like to
explain at a higher level what you are *really* trying to achieve :-)
E.g. "Function m is one of n functions in main.py of which abc.py
may/must call 0, 1, or many because blah blah blah ..."

BTW, "return None" at the very end of a function is redundant. The
Python compiler generates "return None" automagically (implicitly!?)
instead of letting you fall off the end of the world. Which book or
tutorial are you using?

BTW #2: "python25.exe main.py" ?? If you are on Windows, have Python
2.4 as your default setup, and are trialling 2.5: you may like to ask
(in a new thread) about more convenient ways of doing it. Otherwise you
might like to tell what you are up to (in a new thread) so that your
problem can be diagnosed correctly and cured :-)

HTH,
John




More information about the Python-list mailing list