0

I'm trying to split my python code into a few files :

file1.py

from file2 import *

var1 = 7
func_file2()

file2.py

def func_file2():
    var2 = var1

So it says:

NameError: global name 'var1' is not defined

How can I fix that?

I tried to import file1 in file2.

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
Steeven_b
  • 747
  • 2
  • 10
  • 22
  • You should avoid using `*` to import. It clutters your namespace and can cause funny problems when you have two variables with the same names or even variables that have the same name as built-in functions. Just a general tip. – Ian Jun 17 '16 at 09:00
  • Yeah sorry, I just changed my variables name to make it easier to understand, fixed ! – Steeven_b Jun 17 '16 at 09:00
  • and please don't do cyclic imports! read this: http://stackoverflow.com/questions/37756028/import-module-defined-in-another-module/37756322#37756322 – Quirk Jun 17 '16 at 09:00
  • 1
    because in file1.py, you first import everything from fil2.py. You define var1 after the import! – Colonel Beauvel Jun 17 '16 at 09:02
  • Thanks for the answers, I didn't know about cyclic imports, I will take a look to make a proper code :) – Steeven_b Jun 17 '16 at 09:06

3 Answers3

1

var1 is defined in file1 but you are referencing it in file2. You could move var1 to file2 to fix the error.

file1.py

from file2 import *    
func_file2()

file2.py

def func_file2():
    var1 = 7
    var2 = var1

You might be tempted to import file1 in file2 first to define var1 but that would cause a cyclic import (both file1 & file2 would reference each other).

Ken
  • 785
  • 6
  • 11
0

func_file2 doesn't have visibility of your variable var1 because when it's defined the var1 doesn't exist in any scope so the closure doesn't work.

When you write modules in python, follow the principle of cohesion that means that if a function in a module uses a variable from another module something can be wrong.

BangTheBank
  • 809
  • 3
  • 11
  • 26
0

I don't suggest you to use global variables however if you want it to work the way it is now, you can do something like this:

first file
global var1 
var1 = 7

second file
from first_file_name import var1 #this will make your var1 accessible from the second file

I hope it helps.

wind85
  • 487
  • 2
  • 5
  • 11