In Python, Is there a C++ equivalent to declaring a function and defining it after it's used?

Question:

I’m sorry if this has already been answered. I didn’t really know how to search for this particular question.

In C++ you can define a variable at the top to later define. For example:

int printOne();

int main()
{
     cout << printOne() << endl;
     return 0;
}

int printOne
{
     return 1;
}

I’m pretty new to Python though, so I was wondering if this was a possibility for Python as well.

Asked By: Garfield Tong

||

Answers:

you don’t have to. Python evaluates everything at run-time:

def a():
    print(b())

def b():
    return 12

a()

so when a is called b is already defined.

note: that doesn’t work because when a() is called b isn’t defined yet:

def a():
    print(b())

a()

def b():
    return 12

Traceback (most recent call last):
  File "<string>", line 420, in run_nodebug
  File "<module1>", line 4, in <module>
  File "<module1>", line 2, in a
NameError: name 'b' is not defined

There generally isn’t a need. The function only needs to be defined by the time you call the function. For example this would work just fine even though the definition of printOne was after main.

def main():
    print(printOne())

def printOne():
    return 1

main()
Answered By: Cory Kramer

I found this useful when I want to define all my parameters at the top, but their computation depends on not yet declared code:

# Parameter section ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
param_a = 2
# Like to set param_b here for everyone to see, but it depends on big complex functions:
param_b = lambda: compute_param(param_a)
param_c = 'compute_param(param_a)'

# Function section ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

def fn(b = param_b, c = param_c):
    ''' Function using the global parameters defined at the top 
    '''
    if callable(b): 
        b = b()
    c = eval(str(c))
    print(b + c)

def compute_param(x):
    return 3*x

# MAin code section ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if __name__ == '__main__':
    fn() #default params
    fn(10,10) 
Answered By: Adrian Curic
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.