testing python code today tried following code:
(the following runs on python 3.2+, although previous versions raise syntaxerror when del used , variable referenced in enclosing scope)
def x(): n = 200 def y(): print(n) del n y() x() nameerror: free variable 'n' referenced before assignment in enclosing scope as can see, python not raises nameerror: global name 'n' not defined, , made me wondering 1 thing is:
when del statement used withing enclosing scope of function delete free variable that's used inside nested function y function here , thereafter if free variable in our case n deleted through del statement in enclosing scope, del delete name's (n) value , keeps bound enclosing scope ?
a) why raises:
nameerror: free variable 'n' referenced before assignment...rathernameerror: global name 'n' not defined?b) how
deldelete name? unbind value , keep in scope ?
i found similar case here
it works this: when write print(n) inside y not assign n in y, means @ time y defined, python looks in enclosing scopes find nearest 1 name n assigned. doesn't matter whether assignment n happens before or after definition of y, or whether it's later undone del; looks nearest enclosing scope assignment n exists. in case, since n assigned inside x, y makes little note saying "when need n, in scope of x".
so when call y, looks n in scope of x. if isn't there, error. note same error without del if move n = 100 line after call y.
Comments
Post a Comment