Matt Sosna
Matt Sosna

Reputation: 99

Calling Python function that requires libraries from another file

I have a script called "custom_functions.py" with functions I've written to simplify my work. Each custom function calls different libraries. "custom_functions.py" looks something like this:

# This is custom_functions.py
import pandas as pd
import numpy as np

def create_df():
   return pd.DataFrame({'a': [1, 2, 3]})

def create_array():
   return np.array([1, 2, 3])

Over the last few months, as I've added functions to custom_functions.py, there are more and more libraries I need to import for me to be able to call the script into another file (let's call it "main.py"). It seems inefficient/unnecessary to load in the libraries for all the functions when I end up only needing one.

Is there a way to call only e.g. create_array without needing to also load in the libraries required for create_df? It'd be ideal, for example, if I could remove all library calls in custom_functions.py and only import the necessary libraries in main.py before I call in a specific function from custom_functions.py., e.g.:

# This is the proposed custom_functions.py
def create_df():
   return pd.DataFrame({'a': [1, 2, 3]})

def create_array():
   return np.array([1, 2, 3])

and

# This is the proposed main.py
import numpy as np
from custom_functions import create_array

The above code throws an error (NameError: name "np" is not defined). Is the only solution to break custom_functions.py into separate scripts and just load all associated libraries every time I load custom_functions into main.py?

In case it's helpful, I'm using Python 3.6.5 with Anaconda on a Windows 10 machine.

Thanks for your help!

Upvotes: 1

Views: 6020

Answers (2)

nathan.medz
nathan.medz

Reputation: 1603

you could move the imports as @ParitoshSingh suggested but general best practices encourage keeping imports at the top of the file unless you have a specific reason not to. This may seem unnecessary now but as the complexity of your functions increases you can run into problems with circular imports as well as unexpected namespace issues that are often extremely tough to debug/ resolve.

If it really matters to you then you should split your utility functions into different files.

Upvotes: 0

Kyle
Kyle

Reputation: 56

Proper way would be to split it up into different files.

If you really don't want to do that, you can put any imports inside of the functions. Downside to this is every time you call the function the module gets imported again instead of just importing once. If you do this, be as absolutely specific as you can.

def create_array():
    from numpy import array
    return array([1, 2, 3])

Upvotes: 1

Related Questions