Search code examples
pythonpandasmodularity

Working with multiple files in python 2.x


I am new to python and I am writing a long and complex program. For better management I would like to separate the code and call the variable and functions in a main app.py that I will run frequently.

Considering the following two files, how can I correctly import the functions and variables into app.py?

part1.py:

   import pytz
    import json
    import pandas as pd
    import numpy as np

    actual_date = run (...)

    def sqlquery():
        query = """  ..."""
        df = run_query(query)
        return df

    def calcuations():
        df = sqlquery()
        cat_age = df[.....]
        mouse_name = df[.....]
        ....

        if cat>=10:
            color = "good"
            else:
            color = "bad"

    return calcuations()

part2.py:

import pytz
import json
import pandas as pd
import numpy as np

actual_date = run (...)

def sqlquery2():
    query = """  ..."""
    df = run_query(query)
    return df

def calcuations2():
    df = sqlquery()
    cow_age = df[.....]
    horse_name = df[.....]
    ....

    if cow_age>=10:
        color = "good"
        else:
        color = "bad"

return calcuations2()

In app.py I would like to call all the variables and create a json: I tried with from part1 import * but I get an error: NameError: name 'part1' is not defined This is app.py

import pytz
import json
import pandas as pd
import numpy as np
from part1 import *
from part2 import *

def json():

    data_out = {}
    data['animal_age'] = {}
    data['animal_age']['cat'] = cat_age
                .....

    data_out = json.dumps(data_out)
    return data_out

What is the correct way of importing all the variables and functions into app.py?


Solution

  • You are not importing the name part1 at all (just everything inside of it) but you are probably still using it in somewhere in your code which is why you get the error.

    Looking at your part1.py and part2.py files they are very similar and have the same variable names anyway... so it's probably a mistake to import everything from part2 which just overwrites some of what you just imported from part1

    The correct way is to replace

    from part1 import *
    from part2 import *
    

    With

    import part1
    import part2
    

    And use their variables accordingly, like part1.actual_date or part2.actual_date

    That will solve both the error you're getting and the bad practice of filling up your namespace with multiple similar objects (which sometimes even overlap)

    Also the commenters remarks about your code are correct, there are several other errors here which won't allow you to run anything, for example some indentation problems and a return statement outside of a function