8

I have declared a few variables and initialised them with some value in variables.py:

flag = 0
j = 1

I want to use those values in another file main_file.py:

import variables
if(flag == 0) :
 j = j+1

However I get the following error,

NameError: name 'flag' is not defined

How can i solve this problem?

wjandrea
34k10 gold badges69 silver badges107 bronze badges
asked Aug 16, 2017 at 9:57
1
  • 3
    Replace 'flag' with 'variables.flag' Commented Aug 16, 2017 at 9:59

3 Answers 3

10

Everything you've done is right except when using the variables.

In your main_file.py file:

if(variables.flag == 0) :
 variables.j = variables.j + 1

(Or)

Use the following header :

from variables import *

(Or)

from variables import flag, j

Replace all the references of flag and j (or any other variable you want to use from that file) with the prefix 'variables.'

Since this is just a copy of the variable, the values in the variables.py won't get affected if you modify them in main_file.py

answered Aug 16, 2017 at 9:59
Sign up to request clarification or add additional context in comments.

Comments

9

You can either use

import variables

and then access the vairables like this:

variables.flag
variables.j

or you can use:

from variables import flag, j

and then access the vaiables by just their name.

Important:

Please note that in the second case, you will be working with a copy of the variables, and modifying them in one module has no effect on the variables in the other module!

answered Aug 16, 2017 at 10:01

Comments

1

You need to import the variables from the file. You can import all of them like this:

from variables import *
if(flag == 0) :
 j = j+1

Or reference a variable from the imported module like this variables.flag

import variables
if(variables.flag == 0) :
 j = j+1

Or import them one by one like this

from variables import flag, j
if(flag == 0) :
 j = j+1

The best way is to use variables.flag preserving the namespace variables because when your code grows large, you can always know that the flag variable is coming from the module variables. This also will enable you to use the same variable name flag within other modules like module2.flag

answered Aug 16, 2017 at 10:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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