tags:

views:

829

answers:

3

I use Python CGI. I cannot call a function before it is defined.

In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.

Is there such a trick in Python as well?

example:

def do_something(ds_parameter):
    helper_function(ds_parameter)
    ....

def helper_function(hf_parameter):
    ....

def main():
    do_something(my_value)

main()

David is right, my example is wrong. What about:

<start of cgi-script>

def do_something(ds_parameter):
    helper_function(ds_parameter) 
    .... 

def print_something(): 
    do_something(my_value) 

print_something() 

def helper_function(hf_parameter): 
    .... 

def main()
    ....

main()

Can I "forward declare" the functions at the top of the script?

+7  A: 

All functions must be defined before any are used.

However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.

You don't need "forward declaration" because all declarations are completely independent of each other. As long as all declarations come before all executable code.

Are you having a problem? If so, please post the code that doesn't work.


In your example, print_something() is out of place.

The rule: All functions must be defined before any code that does real work

Therefore, put all the statements that do work last.

S.Lott
+2  A: 

Assuming you have some code snippet that calls your function main after it's been defined, then your example works as written. Because of how Python is interpreted, any functions that are called by the body of do_something do not need to be defined when the do_something function is defined.

The steps that Python will take while executing your code are as follows.

  1. Define the function do_something.
  2. Define the function helper_function.
  3. Define the function main.
  4. (Given my assumption above) Call main.
  5. From main, call do_something.
  6. From do_something, call helper_function.

The only time that Python cares that helper_function exists is when it gets to step six. You should be able to verify that Python makes it all the way to step six before raising an error when it tries to find helper_function so that it can call it.

David Locke
A: 

I've never come across a case where "forward-function-definition" is necessary.. Can you not simply move print_something() to inside your main function..?

def do_something(ds_parameter):
    helper_function(ds_parameter) 
    .... 

def print_something(): 
    do_something(my_value) 


def helper_function(hf_parameter): 
    .... 

def main()
    print_something() 
    ....

main()

Python doesn't care that helper_function() is defined after it's use on line 3 (in the do_something function)

I recommend using something like WinPDB and stepping through your code. It shows nicely how Python's parser/executor(?) works

dbr