Search code examples
python-3.xpython-importnameerror

Import variables from another .py file


I am learning python programming and I am stuck in something that is probably very basic but I cannot fix. My problem is: I have a .py file called "Downloading_The_Data" in a directory. This file contains some variables like "HOUSING_PATH" and others. Now, I have another .py file in the same directory and I want to import the other file into it. I simply write "import DOWNLOADING_THE_DATA" and everything works fine except when I try to use the variable "HOUSING_PATH" which seems not imported. The code:

The "DOWNLOADING_THE_DATA" file:

import os
import tarfile
import urllib

DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
HOUSING_PATH = os.path.join("datasets" , "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"

def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
    if not os.path.isdir(housing_path):
        os.makedirs(housing_path)
    tgz_path = os.path.join(housing_path, "housing.tgz")
    urllib.request.urlretrieve(housing_url, tgz_path)
    housing_tgz = tarfile.open(tgz_path)
    housing_tgz.extractall(path=housing_path)
    housing_tgz.close()

The new python file is:

import pandas as pd
import Downloading_The_Data

def load_housing_data(housing_path=HOUSING_PATH):
    csv_path = os.path.join(housing_path , "housing.csv")
    return pd.read_csv(csv_path)

The error is: NameError: name 'HOUSING_PATH' is not defined

I thought I could just import the 'DOWNLOADING_THE_DATA' file and all the variables declared there would be imported so I could use it. Thus, my question is simple and straight: What is wrong and how do I fix it?

edit: just a disclaimer: I know I could use everything in just one file and simply call pandas and everything and load the csv in the same notebook, but it is an exercise I'm doing for myself. I know someday I will need to import other files with its variables and stuff so I am just trying to do this from the beginning.


Solution

  • You should use any definitions from another python file like this:

    import module
    module.variable = 5
    module.class()
    module.function()
    

    or You can do:

    from module import variable, class, function
    variable = 5
    class()
    function()
    

    from module import * is not good practice. If you hate typing, you can give another name:

    from module import variable as var
    var = 5