Calling a function in __main__ from a module?

John J. Lee jjl at pobox.com
Thu Dec 18 20:21:14 CET 2003


Marc Shapiro <mshapiro at sunlitsurf.com> writes:
[...]
> Traceback (most recent call last):
>    File "./hp", line 62, in ?
>      curses.wrapper(main)
>    File "/usr/lib/python2.3/curses/wrapper.py", line 44, in wrapper
>      res = func(stdscr, *rest)
>    File "./hp", line 58, in main
>      mb.mainloop(items)
>    File "/home/mns/menu.py", line 258, in mainloop
>      exec cmd + "('" + name + "')"
>    File "<string>", line 1, in ?
> NameError: name 'NOP' is not defined
> 
> 'NOP' is the name of the function that I am trying to call.  It does
> not exist in the menu module, but is in the calling (hp) module.  I
> can't qualify the name (i.e. __main__.NOP() ) since __main__ can not
> be used for qualification, only called module names can be used that
> way.
> 
> How do I get the module to call functions in a parent module.  Tkinter
> would set up a callback function and bind it to an event.  Can
> something similar be done for a console program using curses?

Stop thinking about 'the parent module'.  The question of *which*
module wants to get at a particular function is irrelevant.  Think
like this instead: you have a bunch of modules, which any piece of
Python code is free to import stuff from, and you have a main program
which can be a module or not as you choose (if it's on sys.path, it's
a module, if it's not, it ain't; if it *is* a module, you'll also have
an if __name__ == "__main__" to prevent the program startup code
getting executed at times other than program startup).

So, you want to get at your NOP function.  Two obvious choices:

1. import it

2. pass it as a function argument

If 1, just make sure the file you want to import it from is on
sys.path (or in a package that's on sys.path; a package is a directory
on sys.path that contains an __init__.py file).  You can always just
grab your program startup code (say, main()), and stick it in a tiny
executable file somewhere convenient like ~/bin, and move any other
code that was originally in the same file into a module.

BTW, I have never yet used exec or eval, and I've written a fair
amount (tens of thousands of lines) of Python code.  Whatever you
think you need them for, you probably don't.


John




More information about the Python-list mailing list