0

Possible Duplicate:
Global Variable from a different file Python

is that possible to set variable in different file ?

So I have two different files somewhat like this..

tes1.py

import test2
st = 'a'
def main():
  mis = input('puts: ')
  print tes2.set(mis)
main()

tes2.py

def set(object):
  pics = ['''
  %s
  1st
  '''%st,
  '''
  %s
  2nd
  ''']
  return pics[object]

and i execute tes1.py and issued an error:

NameError: global name 'st' is not defined

thanks for the respond

Community
  • 1
  • 1
flefin
  • 65
  • 1
  • 9

2 Answers2

1

Yes, but you really don't want to do that. I'd pass st in as an argument to set(). However the following (bad) setup works:

lib.py

var = "woo"

exec.py

import lib
print lib.var

(Note that just importing lib.py into exec.py does not enable me to use variables from exec.py in lib.py, only the other way around. Think about how that applies to your situation.)

Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
1

A few tips:

  • Wrap your main() function in a if __name__ == '__main__' block. It prevents imported modules from executing code that should not be run when being imported. I usually do away with main() completely and just write all my main code in the if block.
  • object is a built-in type. Don't name things object. Also set, as that is a type as well.
  • Global variables are discouraged, as there is always a way to make global variables into parameters (unless your global variables are constants, which is fine).

Here's how I would do it:

test1.py:

import test2

if __name__ == '__main__':
  st = 'a'
  mis = input('puts: ')

  print tes2.rename_me_set(st, mis)

test2.py:

def rename_me_set(st, obj):
  pics = ['''
  %s
  1st
  ''' % st,
  '''
  %s
  2nd
  ''']

  return pics[obj]
Blender
  • 289,723
  • 53
  • 439
  • 496