Importing some functions from a py file

A

Anthony Liu

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
 
J

John Machin

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top