Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function in a separate file in Python [closed]

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!

like image 692
user1590499 Avatar asked Sep 18 '12 13:09

user1590499


People also ask

Can you call a function from a different Python file?

Approach: Create a Python file containing the required functions. Create another Python file and import the previous Python file into it. Call the functions defined in the imported file.

How do you call a function from another file in Jupyter notebook?

py file), or Jupyter Notebook. Remember the file that contains the function definitions and the file calling the functions must be in the same directory. To use the functions written in one file inside another file include the import line, from filename import function_name .

Which function should be used to save and close a file in Python?

The close() Method Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.


2 Answers

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.

like image 56
Pierre GM Avatar answered Sep 20 '22 13:09

Pierre GM


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() 
like image 27
skunkfrukt Avatar answered Sep 18 '22 13:09

skunkfrukt