Importing some functions from a py file

John Machin sjmachin at lexicon.net
Tue Apr 19 23:07:00 EDT 2005


On Tue, 19 Apr 2005 19:13:13 -0700 (PDT), Anthony Liu
<antonyliu2002 at yahoo.com> wrote:
>I think I got confused by the python import facility.
>Say, in code1.py I have func1, func2, func3 and main.
>In code2.py, I *only* want to use func2 from code1.py.
>So, I did
>
>from code1 import func2
>
>But every time, I run code2.py, the main() of code1.py
>is run.
>
>I don't know why.  Any hint please?  Thanks.

*All* of code1.py is executed when you import all or parts of it.

code1.py should look something like this:
===
import some, modules, maybe

def func1():
    do_sth_1()

def func2():
    do_sth_2()

def main():
    do sth_m()

if __name__ == "__main__":
    main()
=== 

The import, the defs, and the "if" and anything else you have at the
top level are statements that are executed.

If you run code1.py as a script, the if test passes, and main() is
invoked. Otherwise (you import all or bits of the code1 module), the
if test fails, and main() is not invoked.

Possibilities: (a) In your real code1.py, you don't actually have "def
main()", you have do_sth_m() at the top level, and it is being
executed unconditionally (b) you do have "def main()" as per my
example, but you have an unguarded "main()" at the top level (c)
something that we can't guess -- you may have to post a more detailed 
description (cut-down version of the actual code would be a good
idea!).

HTH,
John




More information about the Python-list mailing list