0

I am trying to understand how to import code from one file to another. I have two files file1.py and file2.py. I am running code in the first file, and have many variables and functions defined in the second file. I am using from file2 import * to import the code into file1.py. I have no problem using variables defined in file2.py in file1.py, but with functions I am getting NameError: name 'myfunc' is not defined when I try to use the function in file1.py. I can fix this problem by writing from file2 import myfunc, but I thought writing * would import everything from that file. What is the difference for functions versus variables?

  • Take a look here: http://stackoverflow.com/questions/19883870/python-from-x-import-not-importing-everything – Babyburger Jul 29 '16 at 13:27

1 Answers1

0

I have tried to recreate the setup you have described and it is working OK for me. Hopefully this will give you an idea of how to get it to work.

# file1.py #####################################
import sys
sys.path.append("/home/neko/test/")
import file2
if __name__ == "__main__":
    file2.testfunc()

# file2.py ######################################
testvar = 'hello'
def testfunc(): print testvar

For this test I was using python version 2.6.6

Both file1.py and file2.py is in /home/neko/test/

neko
  • 26
  • 3