Why is Python compiling this code without throwing errors?

Viewed 104

I'm new to Python, so please bear with me. Why isn't Python throwing an error when it compiles the following code.

def b_search(left, right):
    while left <= right:
        mid = left + (right-left)//2

        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            left = whatever
        else:
            right = mid-1
    return -1

Wondering how there's no error even though 'nums' isn't defined, and neither is 'whatever', nor 'target'.

Thanks!

2 Answers

Global variables are looked up at runtime, when the function tries to access their value, not when the function is defined. If there's still no nums variable when the function tries to actually use it, you'll get a NameError at that point, but not at function definition time.

The process here isn't "look up nums and compile bytecode using the information we found"; it's "compile bytecode that, if run, might look up nums then".

From the code you provided, looks like you're not running the function, therefore the code is not being executed and it doesn't use the non-existing variables.

Once you declared the function, if you try to call it, you'll find this errors:

>>> b_search(3,9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in b_search
NameError: name 'nums' is not defined
Related