Scopes and exceptions

Hans Nowak ivnowa at hvision.nl
Fri Dec 15 05:58:42 EST 2000


Magnus Heino wrote:
> 
> Could someone please explain this to me:
> 
> [magnus at daysleeper magnus]$ cat e.py
> 
> a = 'test'
> b = 'test'
> 
> print 'a      = %s' % id(a)
> print 'b      = %s' % id(b)
> 
> def func():
>         print "'test' = %s" % id('test')
> 
> func()
> 
> try:
>         test, '%s' % (a,)
> except NameError, e:
>         print 'e      = %s' % id(e)
>         print 'a      = %s' % id(a)
>         print 'b      = %s' % id(b)
>         print "'test' = %s" % id('test')
> 
> [magnus at daysleeper magnus]$ python e.py
> a      = 136227368
> b      = 136227368
> 'test' = 136227368
> e      = 135997204
> a      = 136227368
> b      = 136227368
> 'test' = 136227368
> [magnus at daysleeper magnus]$

I don't understand what is so special about this? Python stores a string
'test' in memory... a points to this string, then b, so id(a), id(b) and
id('test') all yield the same result. This is also the case after the
exception. Variable e has a different id, because it's a different
variable; not a string, but an instance of exceptions.NameError. 

HTH,

--Hans Nowak



More information about the Python-list mailing list