user2629628
user2629628

Reputation: 141

Nested functions in python

I have a function that makes a dictionary based on file input. Then another function that makes a calculation based on the dictionary. These 2 functions are nested in a main function. I.e:

def make_dic():
     data=dict()
     code...
     return data
def make_calculation():
     for x,y in data.items()
     code....
def main():
    data=make_dic()
    make_calculation()

My problem is that I get an error: NameError: name 'data' is not defined

How can I get make_calculation() recognize the dictionary created in make_dic() when they are nested in main()?

Thanks.

Upvotes: 0

Views: 351

Answers (2)

paisanco
paisanco

Reputation: 4164

Pass "data" as a parameter to your make_calculation function:

def make_dic():
     data=dict()
     code...
     return data
def make_calculation(data):
     for x,y in data.items()
     code....
def main():
    data=make_dic()
    make_calculation(data)

The reason you need to do this is due to Python scoping rules (i.e. the location within a program , or "scope" of where a parameter is or is not defined).

Parameter "data" is not a global variable (using global variables is rarely recommended and should be a last resort) , and thus make_calculation(data) needs to receive the element as a parameter, which was defined elsewhere -ultimately the parameter created in make_dic()

@chepner said as much, more formally, in their comment (i.e. Python is lexically scoped). For much more on Python scoping rules see this old, but still useful ,answer : Short description of the scoping rules?

Upvotes: 1

Pythonista
Pythonista

Reputation: 19

in the first function try putting global data, hope it helps.

Upvotes: 0

Related Questions