By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,548 Members | 1,563 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,548 IT Pros & Developers. It's quick & easy.

python function defs/declarations

P: n/a
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

Jul 3 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
bruce <be*******@earthlink.netwrote:
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
Jul 3 '06 #2

P: n/a
bruce wrote:
the docs state that the following is valid...
print "i = "i
Is this a typo or is that really in the docs?
Jul 5 '06 #3

P: n/a
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

Jul 5 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.