1

Is there any way to call a function before its definition.

def Insert(value):
    """place value at an available leaf, then bubble up from there"""
    heap.append(value)
    BubbleUp(len(heap) - 1)

def BubbleUp(position):
    print 'something'

This code shows "unresolved reference BubbleUp"

  • 2
    No, you can't do that. Your code is fine though because `BubbleUp` is not being called before it is defined. – Farhan.K Sep 01 '16 at 10:53
  • 3
    This code _should_ work, since `BubbleUp` is not called when `Insert` is declared, but when it's actually _called_. – tobias_k Sep 01 '16 at 10:54
  • 2
    you are not calling either calls in this code, if you called `Insert` after both definitions then you'd be fine. – Tadhg McDonald-Jensen Sep 01 '16 at 10:55
  • Also, what is "unresolved reference"? Did you get a `NameError`? If this is a warning/error in your IDE: What IDE are you using? – tobias_k Sep 01 '16 at 10:56
  • The `def` line is evaluated at import time, the actual call only when the function is called. So, `BubbleUp` is defined then. But if are using an IDE it might get confused with that and shows an error. – Klaus D. Sep 01 '16 at 10:56
  • Your code is alright as already explained by others, now... if you're using pycharm... could it be your error related to this? [pycharm-shows-unresolved-references-error-for-valid-code](http://stackoverflow.com/questions/11725519/pycharm-shows-unresolved-references-error-for-valid-code) – BPL Sep 01 '16 at 11:03

1 Answers1

6

The code here doesn't show anything, least of all an error, because neither of the functions is called. What matters is the location of the call to Insert, and as long as it comes after BubbleUp (and why wouldn't it), there is no issue. Function definitions don't execute the function body, so you can define functions in whatever order you like, as long as you refrain from calling any of them until all necessary functions are defined.