python function defs/declarations

B

bruce

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'

thanks

-bruce
 
A

Alex Martelli

bruce said:
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
 
B

bearophileHUGS

bruce:
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'

Generally no you can't, you have to define a name before using it.
Why do you want to do that?

Bye,
bearophile
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top