Search code examples
pythonmodulepackagecode-organization

Python code organization help: importing functions


I have written some code, but it's all located in one file. It's sort of annoying to work with now because it's so long. So I'm thinking I should put all the function in a different file and just import them. I'm just not sure about the best way to go about doing this.

Current Code:

import glob, os
import csv as csv
import pandas as pd
import numpy as np
import sys

def create_list(var):      
    stuff
def store_table(var):
    stuff
def geo_info(var):
    stuff 
def factor_loads(var):
    stuff  
def add_loads(var):
    stuff 
def calc_bypass_stress(var):
    a lot of stuff
def calcloads(var): 
    tons of stuff and calls other functions above    

for i in list:
   for k in another_list:
       calcloads(var)

I'm thinking that I could split it up so the functions that do lookups and create tables are in tables.py; anything that calculates stuff is in calc_stuff.py and I run everything from thehead.py:

tables.py

def create_list(var):      
    stuff
def store_table(var):
    stuff
def geo_info(var):
    stuff
def factor_loads(var):
    stuff
def add_loads(var):
    stuff

calc_stuff.py

def calc_bypass_stress(var):
    a lot of stuff
def calcloads(var): 
    tons of stuff and calls other functions above    

thehead.py

import glob, os
import csv as csv
import pandas as pd
import numpy as np
import sys
from tables import *
from calc_stuff import *

for i in list:
   for k in another_list:
       calcloads(var)

Some questions:

1) Will this work?

2) Almost all of my functions use something from Pandas, Numpy, etc. Do I need to import those packages inside each of the .py files? Or just at thehead.py?

3) From thehead.py I'm calling a function (calcloads) that is located in calc_stuff.py which uses functions located in tables.py. Should I have kept all functions in one file as opposed to splitting functions up into different files?


Solution

    1. Yes.
    2. You need to import the packages in each of the .py files.
    3. It's not a problem to split the functions up into different files. If your files are becoming very long, it would definitely be a good idea.