using identifiers before they are defined

MRAB python at mrabarnett.plus.com
Tue Jun 12 14:25:24 EDT 2012


On 12/06/2012 18:53, Julio Sergio wrote:
> 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?
>
In Python, "def" is a statement, not a declaration. It binds the body of 
the function
to the name when the "def" statement is run.

A Python script is, basically, run from top to bottom, and both "def"
and "class" are actually statements, not declarations.

A function can refer to another function, even one that hasn't been
defined yet, provided that it has been defined by the time it is called.

For example, this:

     def first():
         second()

     def second():
         pass

     first()

is OK because it defines function "first", then function "second", then
calls "first". By the time "first" calls "second", "second" has been
defined.



More information about the Python-list mailing list