Importing some functions from a py file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Anthony Liu

    Importing some functions from a py file

    Hi,

    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.

    _______________ _______________ _______________ _____
    Do You Yahoo!?
    Tired of spam? Yahoo! Mail has the best spam protection around
    Yahoo Mail: Your smarter, faster, free email solution. Organize your inbox, protect your privacy, and tackle tasks efficiently with AI-powered features and robust security tools.

  • John Machin

    #2
    Re: Importing some functions from a py file

    On Tue, 19 Apr 2005 19:13:13 -0700 (PDT), Anthony Liu
    <antonyliu2002@ yahoo.com> wrote:[color=blue]
    >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.[/color]

    *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

    Comment

    Working...