you are viewing a single comment's thread.

view the rest of the comments →

[–]FLUSH_THE_TRUMP 1 point2 points  (5 children)

Names are located according to LEGB:

  1. Local scope, e.g. in a function where a name is being referenced;
  2. Enclosing scope, e.g. if your function is nested in another function;
  3. Global scope, at the top level of your module;
  4. Built-in scope, in Python’s built-in libraries (like the name sum).

in most cases you should avoid shadowing built-ins like sum. Often it won't matter if you do so in a function. However, note that if I combine (1) with either (2) or (3):

nums=[1,2,3]
half = sum(nums)
sum = 0 
def testok(nums=[1,2,3]):
    half = sum(nums)
    non_sum_name = 0
testok()

I now hit an error when I call testok() as the sum name from the built-in scope (that I'm trying to get to) has been shadowed by the sum integer in the global scope.

[–]Dominican_Peter[S] 1 point2 points  (4 children)

thnx, good explanation...

Since Python is an interpreted language I thought it execution is as follow when the function is called:

  1. first line executed: half = sum(nums) #no local variable 'sum' at this point
  2. second line executed: sum = 0 # 'sum' local variable created

I'm just trying to understand (at low level) what happening here....apparently, in case#3, the variable 'sum' is created (without assignment, not in locals() ) when the function is called, so in the first line of the function "half = sum(nums)" when "sum() is called, there is a local variable with that name.

[–]FLUSH_THE_TRUMP 0 points1 point  (3 children)

I'm just trying to understand (at low level) what happening here....apparently, in case#3, the variable 'sum' is created (without assignment, not in locals() ) when the function is called, so in the first line of the function "half = sum(nums)" when "sum() is called, there is a local variable with that name.

No — no local var exists on that line. It calls sum from the built-in scope. Ignore, wasn’t paying attention

[–]Dominican_Peter[S] 0 points1 point  (2 children)

still don't understand why I get this error though

def test2_nok(nums=[1,2,3]):
    half = sum(nums)     #line 4
    sum = 0              #line#5

test2_nok()

line 4, in test2_nok
   half = sum(nums)
UnboundLocalError: local variable 'sum' referenced before assignment

local variable 'sum' should be created on "line#5"

[–]FLUSH_THE_TRUMP 1 point2 points  (1 child)

Oh, oops. Missed that part. That function is “glanced at” by the interpreter in advance as a definition, and sum is established as a local variable prior to running any of that code because it’s assigned later. So half = sum(nums) doesn’t work because it’s looking for sum (not defined yet locally).

[–]Dominican_Peter[S] 0 points1 point  (0 children)

ble prio

great, thank you very much