Reputation: 2617
Suppose I have two files. The first one contains all the functions I've written and which I usually import from my main file:
# my_functions.py
def sqrt_product(a, b):
from math import sqrt
return sqrt(a*b)
def create_df(lst):
from pandas import DataFrame as df
return df(lst)
and my main file:
# main.py
from my_functions import sqrt_product, create_df
print(sqrt_product(3, 3))
print(create_df([1, 2, 3])
Is there a more efficient way to import this function? Do I have to import every module for every function I create? WHat if I have several functions in the same file that relies on the same module?
Upvotes: 3
Views: 7677
Reputation: 25639
This is how.
import my_functions as repo
Usage:
repo.sqrt_product(a, b)
repo.create_df(lst)
print(repo.sqrt_product(3, 3))
print(repo.create_df([1, 2, 3])
"repo" is now in the namespace. Just like import pandas as pd
, pd
is in namespace.
# my_functions.py
from math import sqrt
from pandas import DataFrame as df
#Or import pandas as pd
def sqrt_product(a, b):
return sqrt(a*b)
def create_df(lst):
return df(lst)
#return pd.DataFrame(lst)
Upvotes: 5
Reputation: 18467
You can move the from pandas import DataFrame
(optionally with as df
) to the top of my_functions.py
and redefine create_df
just to be:
def create_df(lst):
return DataFrame(lst) # or df(lst) if you used as
The create_df
function will still work when you import it without requiring you to import anything from pandas
. It will be imported with everything it needs to do its thing.
This isn't just true for imported dependencies.
x = 5
def y():
return x
If you go somewhere else and import y
, you will find that y()
returns 5, whether or not you imported x
. Whatever the function object needs to do its job, it carries with it. This includes when it is imported into another module.
Upvotes: 1
Reputation: 583
There are a few ways to do this.
Import the file from the current directory.
make sure both files are in the same directory.
Import the file and function like so:
from thing_to_import_from import function_to_import1, function_to_import2
Import the file from another directory.
If the file is in a folder or subfolder within the same directory, and the path contains no spaces, it can be imported like so:
from folder/subfolder/thing_folder/thing_to_import_from import function_to_import
else, add the path to the python sys.path, then import as before.
import sys
sys.path.insert(0, "/folder/subfolder/thing folder")
from thing_to_import_from import function_to_import
Make the file into a python module.
You should ONLY do this if you intend to use the file with multiple programs for an extended period of time. Don't junk up your Lib folder!
Import your script as a module!
from thing_to_import_from import function_to_import
Upvotes: 0
Reputation: 133
U can do this as well.
# main.py
from my_functions import *
print(sqrt_product(3, 3))
print(create_df([1, 2, 3])
Upvotes: 0