2

I am learning python at the moment, after learning Java, now I know that java first compiles the whole file and then run it, in python from what I understand it run the program while it compiles it "line by line".

So what I don't understand is how can I call a function before I define it. I am used from Java to write all my "helping methods" after the method that need them, I think it's easier to read that way. So I tried to do the same thing in python, and it worked. Why?

elii236
  • 98
  • 4
  • a [mre] would be in place here, as people are not sure what you mean. A small piece of code demonstrating what you mean (a function called before it is defined) will greatly help improve your question – Tomerikoo Dec 17 '19 at 21:41

4 Answers4

4

An important designation here is that it is not the order in which the functions are created that matters, it matters when the call to the function is done.

Take for example the following code:

def add_one(new):
    return my_add(new, 1)

def my_add(x, y):
    return x + y

my_var = 2
print("The value of my_var is: {}".format(my_var))
my_var = add_one(my_var)
print("The value of my_var is: {}".format(my_var))

It yields

The value of my_var is: 2

The value of my_var is: 3

This is happening because by the time the add_one function is called, both functions already exist. But if try and call add_one before defining my_add...

def add_one(new):
    return my_add(new, 1)

my_var = 2
print("The value of my_var is: {}".format(my_var))
my_var = add_one(my_var)
print("The value of my_var is: {}".format(my_var))

def my_add(x, y):
    return x + y

We get:

The value of my_var is: 2
Traceback (most recent call last):
  File "c:\Users\wundermahn\Desktop\Stack.py", line 6, in <module>
    my_var = add_one(my_var)
  File "c:\Users\J39304\Desktop\Stack.py", line 2, in add_one
    return my_add(new, 1)
NameError: name 'my_add' is not defined

See Does the order of functions in a Python script matter? for more

Community
  • 1
  • 1
artemis
  • 6,857
  • 11
  • 46
  • 99
0

You can't call a function before it is defined. This program will throw an exception:

foo()

def foo():
    print("Hello from foo")

If this isn't what you meant, please update your question to be more specific.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • *I am used from Java to write all my "helping methods" after the method that need them [...] So I tried to do the same thing in python, and it worked. Why?* – Tomerikoo Dec 17 '19 at 21:38
  • @Tomerikoo I don't understand your comment. I made up a very simple code example to show that calling a function before it is defined _does not work_ in python, contrary to the claim in the question; and therefore clarification is required. – John Gordon Dec 17 '19 at 22:39
  • OP describes a very specific scenario and wonders how it is possible. I agree the question itself is not very clear, but then don't answer it anyway... – Tomerikoo Dec 18 '19 at 08:21
0

The short answer is: you can't

Most longer python programs include a statement like this:

if __name__ == "__main__":
    # do something which is usually call a 'main()' function

at the very end of their main script which means that contents of the if statement is only executed if this file is the one executed, as opposed to being imported.

All the functions must be defined prior to being called, and by the time it hits that if statement at the bottom of the file, they've all been defined.

MoonMist
  • 1,232
  • 6
  • 22
  • @Tomerikoo that's because the code doesn't actually execute. The function just states that when this code is executed, I need to call another function called `foo` or whatever, even though foo might not be defined. By the time that the code actually executes, if there's no function called `foo` that's been defined, it will crash – MoonMist Dec 17 '19 at 21:46
  • what are you talking about? there is no `foo` in your answer? BTW, my previous comment is a quote from the question, not my wording – Tomerikoo Dec 17 '19 at 21:48
  • `foo` is just a placeholder for a madeup function name. I'm aware it wasn't in my answer, it was just an example – MoonMist Dec 17 '19 at 21:50
0

To add to the other answers, I just want to mention that while the code execution at runtime is sequential, when the interpreter hits a function definition, only the definition line gets executed. Here is to citing the documentation:

The function definition does not execute the function body; this gets executed only when the function is called. ...

This also leads to the noteworthy behavior of mutable types as default parameter values. It's good to know about this, as things can turn out pretty surprising otherwise:

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:  # this conditional ensures the expected behavior
        penguin = []
    penguin.append("property of the zoo")
    return penguin
sammy
  • 857
  • 5
  • 13