python function defs/declarations

Alex Martelli aleax at mac.com
Sun Jul 2 20:55:05 EDT 2006


bruce <bedouglas at earthlink.net> wrote:

> hi..
> 
> the docs state that the following is valid...
> 
> def foo():
>  i = 2
>  print "i = "i
> 
> print "hello"
> foo()
> 
> 
> is there a way for me to do this..
> 
> print "hello"
> foo()
> 
> def foo():
>  i = 2
>  print "i = "i
> 
> ie, to use 'foo' prior to the declaration of 'foo'

There are no declarations in Python.  "def" is an executable statement:
when executes it binds a new function object to the given name.

So, your request is like asking to do, say:

print "hello"
print wap

wap = "world"

At the time you use name wap, nothing is bound to it; the fact that
something would later be bound to it (if the binding statement, here an
assignment but that's exactly as much of an executable statement as a
def!) is pretty clearly irrelevant.  Having a clear idea about these
issues is why it's important to remember the distinction between
executable statements (including def, class, assignments, ...) and
declarations (which Python does not have).

You can probably wrap your code in a function, and call it at the end:

def main():
  print "hello"
  foo()

def foo(): ...whatever...

main()


By the time the body of main executes, "def foo" has already executed,
so global name foo is happily bound and everything works fine.

Wrapping most substantial code inside functions is VERY advisable anyway
-- just put just about all the code you'd like to have at module top
level (except for def, class and assignments to "module constants") into
a function (conventionally named main) and call that function at the
very end of the module (ideally within an "if __name__=='__main__":"
guard, but that's a different issue!).


Alex



More information about the Python-list mailing list