Must function defs appear earlier than calls?

SeeBelow at SeeBelow.Nut SeeBelow at SeeBelow.Nut
Tue May 4 21:55:52 EDT 2004


Daniel Yoo wrote:
> 
> SeeBelow at seebelow.nut wrote:
> : Must function defs appear earlier in a file than use of their name?
> 
> : If so, is there some way around this?  It's creating a puzzle for me.
> 
> Let's work on a concrete example.  Say we want to write something like
> this:
> 
> ###
> print square(42)
> 
> def square(x):
>     return x * x
> ###
> 
> This doesn't work, because when Python hits the 'print square(42)'
> statement, it's not aware yet of what 'square' means.  But there is a
> way around this:
> 
> ###
> def main():
>     print square(42)
> 
> def square(x):
>     return x * x
> 
> if __name__ == '__main__':
>     main()
> ###
> 
> Here, we enclose the main flow of our program in a function called
> main().  Python doesn't evaluate a function's body until it is called,
> so by the time that we hit:
> 
>     if __name__ == '__main__':
>         main()
> 
> we're ok, since both main() and square() are defined.
> 
> So to answer your question:
> 
> : Must function defs appear earlier in a file than use of their name?
> 
> we can allow the use to be earlier in terms of location in the source
> file, by using a function definition to delay the evaluation till all
> the symbols are in place.
> 
> Hope this helps!

Yes, this is good info!

thanks,

Mitchell Timin

-- 
"Many are stubborn in pursuit of the path they have chosen, few in
pursuit of the goal." - Friedrich Nietzsche

http://annevolve.sourceforge.net is what I'm into nowadays.
Humans may write to me at this address: zenguy at shaw dot ca



More information about the Python-list mailing list