Profilo di 
  
    Bageyelet
  
  
    
  
    
      
    
  
      
  
      
    | Nome | Bageyelet | 
|---|---|
| Indirizzo email | n/a | 
| Messaggi | 1 | 
- 
      
- 2018-01-10 12:03:49
 - Scope delle variabili nel try-except
 - Forum >> Programmazione Python >> Scripting
 - Stavo facendo degli esperimenti in Python 2.7 e mi sono imbattuto nel seguente errore; lanciando questo script
import sys import resource MEMORY_LIMIT = 1024 * 1024 * 1 # 1 MiB def memory_limit(): resource.setrlimit(resource.RLIMIT_AS, (MEMORY_LIMIT, MEMORY_LIMIT)) memory_limit() s = "" while 1: try: s += "a" except MemoryError: print len(s) sys.exit(0)
ottengo un NameError alla riga print len(s). Il traceback completo è:Traceback (most recent call last): File "limit.py", line 16, in <module> print len(s) NameError: name 's' is not defined
La stranezza risiede nel fatto che s è definita ed inizializzata nello scope globale. Cosa mi sfugge? Notare che il seguente script termina correttamentefrom random import randint import sys def foo(): if randint(0, 100) == 23: raise Exception else: return "a" s = "" while 1: try: s += foo() except: print len(s) sys.exit(0)Grazie in anticipo dell'aiuto
 
 
  