1

I have a problem with including a function from another file to main executable script. I have too many functions and my main script became too long and hard to manage. So i've decided to move every function to separate file and than attach/include it. I've read nearly any relative post here to resolve my problem but no luck. Let's see:

main_script.py
==================
from folder.another_file import f_fromanotherfile

class my_data:
     MDList=[]

work=my_data()

def afunction():
    f_fromanotherfile()
    return

and

another_file.py
=====================
#In this file i've put just function code
def f_fromanotherfile():
    a=[1,2,3,4]
    work.MDList=a
    return

And this is the error:

line 11, in f_fromanotherfile work.MDList=a NameError: global name 'work' is not defined

Help me please

Riggun
  • 195
  • 15
  • 1
    Neither of these files are even syntactically correct Python (missing colons). – Scott Hunter Jan 26 '16 at 01:28
  • Possible duplicate of [How to call a function from another file in Python?](http://stackoverflow.com/questions/20309456/how-to-call-a-function-from-another-file-in-python) – midori Jan 26 '16 at 01:30
  • It seems your problem is that the function `f_fromanotherfile()` has no access to `work`, which is what the error is telling you. `work` must be defined within the scope of `another_file.py`, or better yet, pass it as an argument to the function itself. – Reti43 Jan 26 '16 at 01:32
  • Your error isn't because you are calling the function from another file. It's because you are trying to access a global variable from `main_script.py`, it's a namespaceing issue. Look at this answer - http://stackoverflow.com/a/423401/1760335 – Bert Jan 26 '16 at 01:33

2 Answers2

1

The scope of 'work' is its module, main_script.py, so you cannot access it from another module. Make 'work' an argument of f_fromanotherfile instead:

In another_file.py:

def f_fromanotherfile(work):
  # function body stays the same

In main_module.py:

def afunction():
  f_fromanotherfile(work)
Jochen Müller
  • 309
  • 1
  • 6
1

because in another_file.py

#In this file i've put just function code
def f_fromanotherfile():
    a=[1,2,3,4]
    work.MDList=a
    return 

work is not a global variable.And then doing assignment to it can't work.

u should change ur code to: another_file.py

#In this file i've put just function code
def f_fromanotherfile():
    global work
    a=[1,2,3,4]
    work.MDList=a
    return

with the global keyword u can say the variable in so-called global scope and do ur assignment.

PS:kind of like the keyword extern in C?

herokingsley
  • 403
  • 3
  • 10
  • Are you sure you haven't forgotten something? Your suggested solution seems similar to what the OP already has. – Reti43 Jan 26 '16 at 03:07