0

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.

user2629628
  • 161
  • 1
  • 3
  • 11
  • pass it as an argument to `make_calculation`? – Robin Zigmond Jul 17 '21 at 19:59
  • Python is *lexically* (or statically) scoped. `make_calculations` looks in the scope where it is *defined*, not the scope where it is *called*, for a definition of the free variable `data`. – chepner Jul 17 '21 at 20:00
  • 2
    ("Nested function" usually refers to a function *defined* in another function, not just one that is called in another.) – chepner Jul 17 '21 at 20:01
  • There are *dynamically* scoped languages (shells like `bash`, Lisp, etc), but lexical scoping is widely considered to be easier to reason about. – chepner Jul 17 '21 at 20:03

2 Answers2

1

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?

paisanco
  • 4,098
  • 6
  • 27
  • 33
0

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

Pythonista
  • 19
  • 3