How do I access a main frunction from an import module?
Carl Banks
pavlovevidence at gmail.com
Fri Nov 24 09:39:54 EST 2006
Jim wrote:
> 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()
> ######################
You can do it with "from __main__ import m" atop abc.py (the module
invoked at the command line is always called __main__).
However, I *highly* suggest you put m in another file. Importing
variables from __main__ would make your program incompatible with many
useful tools. For example, if you invoke the Python profiler on your
code, like this:
python -m profile main.py
it will break your code, because __main__ no longer refers to main.py
but to profile.py (from the Python library). Importing from __main__
adversely affects tools such as PyChecker and PyLint.
The exception to this would be if abc.py is specifically designed as a
utility for interactive use; then it would be ok and useful.
Carl Banks
More information about the Python-list
mailing list