Issue
Let's say I have two functions in my script: sum_numbers
and print_sum
. Their implementation is like this:
def sum_numbers(a, b):
return a + b
def print_sum(a, b):
print(sum_numbers(a, b))
So my question is: does the order in which the function are written matter? If I had written the print_sum
function first and then the sum_numbers
, would the code still work? If the answer is yes, does it always work?
Solution
The only thing that Python cares about is that the name is defined when it is actually looked up. That's all.
In your case, this is just fine, order doesn't really matter since you are just defining two functions. That is, you are just introducing two new names, no look-ups.
Now, if you called one of these (in effect, performed a look-up) and switched the order around:
def print_sum(a, b):
print(sum_numbers(a, b))
print_sum(2, 4)
def sum_numbers(a, b):
return a + b
you'd be in trouble (NameError
) because it will try to find a name (sum_numbers
) that just doesn't exist yet.
So in general, yes, the order does matter; there's no hoisting of names in Python like there is in other languages (e.g JavaScript).
Answered By - Dimitris Fasarakis Hilliard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.