using identifiers before they are defined

Jose H. Martinez josehmartinezz at gmail.com
Tue Jun 12 14:16:47 EDT 2012


You should define the function first and then call it.


 def something(i):
     return i

a = something(5)

If you want a reference to the function somewhere else you can do this:

global alias = something

print alias(i)



On Tue, Jun 12, 2012 at 1:53 PM, Julio Sergio <juliosergio at gmail.com> 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?
>
> Thanks,
>
> --Sergio.
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120612/931a6997/attachment.html>


More information about the Python-list mailing list