why del is not a function or method?

Thomas Jollans tjol at tjol.eu
Mon Oct 16 17:57:39 EDT 2017


On 16/10/17 21:12, Stefan Ram wrote:
> ram at zedat.fu-berlin.de (Stefan Ram) writes:
>> »x = None« observably has not the same effect as »del x«:
> 
>   Paradoxically, /deleting/ a local variable which did not
>   ever exist, has the effect of creating a ghost of that
>   local variable which then will hide a global variable:
> 
>   Case 1: The global variable »x« can be used in »f« just
>   fine:
> 
> |>>> x = 9
> |>>> def f():
> |...     print( x )
> |...
> |>>> f()
> |9
> 
>   . Case 2: The »del x« creates a ghost »local variable 'x'«
>   which now will hide the global variable »x«:
> 
> |>>> x = 9
> |>>> def f():
> |...     del x
> |...     print( x )
> |...
> |>>> f()
> |UnboundLocalError: local variable 'x' referenced before assignment
> 
>   .

That's not what happens. The UnboundLocalError is in the del statement,
not the print call:

 >>> x = None
 >>> def f():
 ...     del x
 ...
 >>> f()
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 2, in f
 UnboundLocalError: local variable 'x' referenced before assignment
 >>>




More information about the Python-list mailing list