Calling a function in a separate file in Python
Question:
I’ve read the following posts:
Importing Module or From Module 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!
Answers:
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.
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.
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()
I’ve read the following posts:
Importing Module or From Module 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!
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.
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.
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()