Kurda Yon a écrit :
Hi,

I would like to declare a global variable, which is seen to a
particular function.

First point : there's no real 'global' scope in Python. 'global' really means 'module-level'.

Second point : globals are Bad(tm) anyway.

If I do as the following it works:

x = 1
def test():
  global x
  print x
  return 1

You don't even need the global statement here, since you're not rebinding x within the function.

However, it does not helps since my function is in a separate file. In
other words I have a main program which has the following structure:

from test import test
x = 1
y = test()

That's obviously something you *don't* want - functions depending on global variables that can be changed from anywhere. Ok, like any golden rule, this one is meant to be bypassed sometimes, but unless you fully understand why this is 99 times out of 100 a BadThing(tm) to do, just don't do it.

for the record, this would work:

import test
test.x = 42
y = test()

But once again : unless you really know what you're doing and why you're doing it, just don't do it.

and I have a test.py file which contains the "test" function:
def test():
  global x
  print x
  return 1

In this case the test does not see the global variable x. How can I
make the x to be visible?

Pass it to the function.

# test.py
def test(x):
   print x
   return x + 42

# main.py
from test import test
y = test(2)

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to