简体   繁体   中英

Global Variable Reference inside a function

I'm trying to reference a global variable inside a function. This function is being defined in a separate file and imported into the main file and applied to a dataset. Here's code:

def to_nominal(dataset):
    global ngdp
    global gdp_deflator_series
    
    bools = []
    for date in ngdp.Date:
        if date in set(dataset.Date).intersection(set(ngdp.Date)):
            bools.append(True)
        else: bools.append(False)
    
    npci_deflator_series = gdp_deflator_series[bools].reset_index(drop = True)
    
    bools = []
    for date in dataset.Date:
        if date in set(dataset.Date).intersection(set(ngdp.Date)):
            bools.append(True)
        else: bools.append(False)
        
    dataset_bools = dataset[bools]
    dataset = dataset_bools.reset_index(drop = True).drop(['YEAR', 'QUARTER', 'Date'], axis = 1).mul(npci_deflator_series, axis =0)
    dataset['Date'] = dataset_bools.Date
    return dataset

I throws the error: 'ngdp' not defined. Initially I though this was because I had to specify that ngdp was a global variable, but the problem seems to persist. I think it might have to do with the fact that i'm importing the function into another file? Any thoughts will be appreciated.

From your description, it sounds like this function is being defined in module A , and imported into another module, B , that has ngdp in it's own globals, and you want A.to_nominal to make use of B.ngdp .

That's not possible. Global scope is tied to the module where the function is defined; even when you import the function into another module, it still looks for globals in the original module's ( A ) scope.

You need to either define both the global and the function in the same module (the simplest approach), or tie them together in some other way (ideally not via a circular import, with A importing ngdp , while B imports to_nominal , because that's error-prone as all get out). If they can't be in the same module, simply passing ngdp as an argument to to_nominal would be a reasonable solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM