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.

5
  • 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. Commented Jun 17, 2016 at 9:00
  • Yeah sorry, I just changed my variables name to make it easier to understand, fixed ! Commented Jun 17, 2016 at 9:00
  • and please don't do cyclic imports! read this: stackoverflow.com/questions/37756028/… Commented Jun 17, 2016 at 9:00
  • 1
    because in file1.py, you first import everything from fil2.py. You define var1 after the import! Commented Jun 17, 2016 at 9:02
  • Thanks for the answers, I didn't know about cyclic imports, I will take a look to make a proper code :) Commented Jun 17, 2016 at 9:06

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Is it common to use getters in Python or I should use this way of coding ?
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.