Must function defs appear earlier than calls?
Daniel Yoo
dyoo at hkn.eecs.berkeley.edu
Tue May 4 20:57:56 EDT 2004
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!
More information about the Python-list
mailing list