Vini Salazar
Vini Salazar

Reputation: 11

Python function doesnt work properly when imported, only when locally defined

I have a file called functions.py in my project directory which contains a few simple functions.

One of these functions (load()) is supposed to create global variables without requiring the user to define them beforehand.

When I import the functions from the file using

from functions import load

It doesn't work properly, meaning the global variables are not created.

However, when I copy paste the function to define it instead of importing from the file, it works properly. Here is the complete function:

def load(cnv):

    global hd1, hd2, variables, datapoints
    hd1, hd2, variables, datapoints  = [], [], [], []

    o = open(cnv)
    r = o.readlines()
    o.close()

    for line in r:
        if not line:
            pass
        elif line.startswith('*'):
            hd1.append(line)
        elif line.startswith('#'):
            hd2.append(line)
            if line.startswith('# name'):
                line = line.split()
                variables.append(line[4])
        else:
            float_list = []
            line = line.split()
            for item in line:
                float_list.append(float(item))
            datapoints.append(float_list)

    datapoints = filter(None, datapoints)

    global df
    df = pd.DataFrame(datapoints, columns = variables)

By the way there is an indent in the whole body of the function after the def() statement. I'm not sure why it doesn't appear when I paste it in this post.

I am very new to programming so I'm taking suggestions on how to potentially improve this code.

Thanks in advance.

Upvotes: 0

Views: 768

Answers (2)

Harry
Harry

Reputation: 318

It depends how you use it. For using global you need to first call load function to initialize the variables after which u can use it using the package.variable.

Please find the below implementation.

#functions.py
def load():
    global hd1
    hd1 = []

#test.py
import functions
functions.load()
functions.hd1.append('hey')
print functions.hd1

OR

#test.py
from functions import load
load()
from functions import *
hd1.append('hey')
print hd1

Upvotes: 0

Sergey Vasilyev
Sergey Vasilyev

Reputation: 4189

The "global" variables are not really global to the scope of the whole script. This is not PHP.

Python has everything structure to the per-module namespaces. The variables are "global" to the scope of the module, where that function is declared. So, when you import the function and call it, it creates the variables which can be accessed as functions.hd1, functions.hd2, etc.

Upvotes: 1

Related Questions