51

I've read the following posts:

Importing Module or From Module Import

From file.py import *

And I was just wondering how to know when to break-up my code into multiple files versus putting many functions in one file? My specific problem here is that I have a function with 100 lines that I want to call in the for-loop of another function. Also, when are scripts executed? When you import them, or when you call them?

Note: The answers below have fully solved the problem. Thank you!

Community
  • 1
  • 1
user1590499
  • 933
  • 3
  • 10
  • 17
  • 2
    Why the downvote? Per http://stackoverflow.com/faq, this is a "practicable, answerable problem unique to the programming profession" and a "specific programming problem." Is there a reason for it? – user1590499 Sep 18 '12 at 13:37
  • From http://stackoverflow.com/questions/how-to-ask: "Do your homework. Have you thoroughly searched for an answer before asking your question?" Importing is a basic aspect of Python, well covered in the tutorial and elsewhere. We're *not* here to read the tutorial for you. – Matthew Trevor Sep 18 '12 at 22:02
  • 3
    Upvoting the question as I've decided that Kev is not a real moderator – Stumbler Apr 28 '16 at 18:49

3 Answers3

61

Assuming that the function useful_function is in a file foreign_code.py in the same directory as your program file, just put

from foreign_code import useful_function

at the top of your program.

Pierre GM
  • 19,809
  • 3
  • 56
  • 67
  • 10
    What about the case when program that is using the function and program that is defining the function are in different directories.. – Trojosh Oct 21 '16 at 09:55
8

Depending on the nature of the other file, importing it may be a good solution.

from otherfile import big_function

for something something:
    big_function()
skunkfrukt
  • 1,550
  • 1
  • 13
  • 22
  • 3
    It's a tad better to use `frmo otherfile import big_function` itself, to avoid calling `otherfile.big_function` repeatedly (remember, each `.` is a function call in Python). – Pierre GM Sep 18 '12 at 13:22
  • @PierreGM Good point. I've updated my answer accordingly. – skunkfrukt Sep 18 '12 at 13:25
4

You need to import the other file (or only the function name from that file). Look at the tutorial on modules for reference. Don't forget that scripts are executed when you import them.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175