using identifiers before they are defined

Julio Sergio juliosergio at gmail.com
Tue Jun 12 13:53:31 EDT 2012


I'm puzzled with the following example, which is intended to be a part of a 
module, say "tst.py":

  a = something(5)

  def something(i):
      return i



When I try: 

->>> import tst

The interpreter cries out:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tst.py", line 11, in <module>
    a = something(5)
NameError: name 'something' is not defined

I know that changing the order of the definitions will work, however there are 
situations in which referring to an identifier before it is defined is 
necessary, e.g., in crossed recursion. 

So I modified my module:

  global something

  a = something(5)


  def something(i):
      return i


And this was the answer I got from the interpreter:

->>> import tst

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tst.py", line 12, in <module>
    a = something(5)
NameError: global name 'something' is not defined


Do you have any comments?

Thanks,

--Sergio.







More information about the Python-list mailing list