By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,575 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

Importing some functions from a py file

P: n/a
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
http://mail.yahoo.com
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Tue, 19 Apr 2005 19:13:13 -0700 (PDT), Anthony Liu
<an***********@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

Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.