[Commits] python.it commit r300 - python/contrib/faq/trunk

commit a svn.python.it commit a svn.python.it
Gio 11 Ott 2007 03:54:47 CEST


Author: eriol
Date: Thu Oct 11 03:54:43 2007
New Revision: 300

Modified:
   python/contrib/faq/trunk/programming.ht
Log:
Completata traduzione a cura di Antonio Valente. Revisione effettuata da me

Modified: python/contrib/faq/trunk/programming.ht
==============================================================================
--- python/contrib/faq/trunk/programming.ht	(original)
+++ python/contrib/faq/trunk/programming.ht	Thu Oct 11 03:54:43 2007
@@ -9,7 +9,7 @@
 :Date: $Date: 2005-12-22 06:00:52 +0100 (gio, 22 dic 2005) $
 :Version: $Revision: 8721 $
 :Web site: http://www.python.org/
-:Traduzione: Daniele Tricoli 6 Aprile 2006
+:Traduzione: Daniele Tricoli, Antonio Valente 6 Aprile 2006
 
 .. contents::
 .. sectnum::
@@ -19,10 +19,11 @@
 
 Questo documento, di pubblico dominio, è stato tradotto da 
 `Daniele Tricoli <mailto:eriol a mornie.org?subject=Traduzione Programming FAQ>`_
+e (in maggior parte) da
+`Antonio Valente <mailto:y3s a katamail.com?subject=Traduzione Programming FAQ>`_
 (revisionato da 
-`Meo Bogliolo <mailto:meo a bogliolo.name?subject=Traduzione Programming FAQ>`_ 
-): potete contattarli per qualsiasi
-commento o correzione.
+`Daniele Tricoli <mailto:eriol a mornie.org?subject=Traduzione Programming FAQ>`_
+): potete contattarli per qualsiasi commento o correzione.
 
 Domande Generali
 ===========================
@@ -206,7 +207,7 @@
 inviare l'output ai dispositivi di output utilizzando scritture più grandi
 piuttosto che più piccole in modo da ridurre l'overhead delle chiamate di
 sistema del kernel. Pertanto script CGI che scrivono l'output un "una volta"
-possono essere piò veloci di quelli che effettuano tante scritture di
+possono essere più veloci di quelli che effettuano tante scritture di
 piccole parti di output.
 
 Inoltre, ricordate di utilizzare le caratteristiche base di Python dov'è
@@ -224,177 +225,179 @@
   L2 = list(L1[:3]) # "list" è ridondante se L1 è una lista.
 .. [- MARK -] BEGIN PART 003 of 18
 
-Note that the functionally-oriented builtins such as 
-``map()``, ``zip()``, and friends can be a convenient
-accelerator for loops that perform a single task.  For example to pair the elements of two
-lists together::
+Notare che l'utilizzo di costrutti built-in di tipo funzionale come
+``map()``, ``zip()``, e altri, può fornire un'ottima accelerazione
+per cicli che eseguono una singola operazione. Per esempio, per appaiare
+gli elementi di due liste:
 
   >>> zip([1,2,3], [4,5,6])
   [(1, 4), (2, 5), (3, 6)]
 
-or to compute a number of sines::
+o per calcolare alcuni valori del seno:
 
   >>> map( math.sin, (1,2,3,4))
   [0.841470984808, 0.909297426826, 0.14112000806,   -0.756802495308]
 
-The operation completes very quickly in such cases.
+L'operazione è molto rapida in casi simili.
 
-Other examples include the ``join()`` and ``split()``
-methods of string objects.  For example if s1..s7 are large (10K+) strings then
-``"".join([s1,s2,s3,s4,s5,s6,s7])` may be far faster than
-the more obvious ``s1+s2+s3+s4+s5+s6+s7``, since the "summation"
-will compute many subexpressions, whereas ``join()`` does all the
-copying in one pass.  For manipulating strings, use
-the ``replace()`` method on string objects. Use
-regular expressions only when you're not dealing with constant string patterns.
-Consider using the string formatting operations
-``string % tuple`` and ``string % dictionary``.  
-
-Be sure to use the ``list.sort()`` builtin method to do sorting, and see
-the `sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ for examples of moderately advanced usage.
-``list.sort()`` beats other techniques for sorting in all but the most
-extreme circumstances.
-
-Another common trick is to "push loops into functions or methods."
-For example suppose you have a program that runs slowly and you
-use the profiler to determine that a Python function ``ff()``
-is being called lots of times.  If you notice that ``ff ()``::
+Altri esempi possono essere i metodi ``join()`` e ``split()`` delle stringhe.  
+Per esempio, se s1..s7 sono stringhe molto grandi (10K+), il costrutto
+``"".join([s1,s2,s3,s4,s5,s6,s7])` in genere è molto più veloce del più ovvio
+``s1+s2+s3+s4+s5+s6+s7``, poiché l'applicazione ripetuta dell'operatore "somma"
+crea molte sottoespressioni (NdT: le sottostringhe parziali generate dalle varie somme), 
+mentre ``join()`` esegue tutte le copie in un solo passo.
+Per manipolare le stringhe, invece, conviene usare il metodo ``replace()`` sugli oggetti stringa, 
+mentre conviene usare le espressioni regolari solo se non si ha a che fare con pattern costanti.
+Un'altra possibilità è usare l'operatore di formattazione delle stringhe:
+``string % tuple`` oppure ``string % dictionary``.  
+
+L'ordinamento andrebbe sempre fatto con il metodo builtin ``list.sort()``,
+per esempi di utilizzo (moderatamente) avanzato, c'è il 
+`sorting mini-HOWTO <http://wiki.python.org/moin/HowTo/Sorting>`_ 
+``list.sort()`` è migliore di altri metodi di ordinamento praticamente in
+tutti i casi, tranne qualcuno dei più estremi.
+
+Un altro trucco comunemente usato è di "nascondere" i cicli in funzioni o metodi.
+Per esempio, supponiamo di avere un programma lento e di trovare, usando il profiler,
+che la funzione ``ff()`` viene chiamata moltissime volte. Supponiamo che tale funzione ``ff ()``::
 
    def ff(x):
-       ...do something with x computing result...
+       ...fa qualcosa con x calcolando result...
        return result
 
-tends to be called in loops like::
+tenda ad essere chiamata in cicli come::
 
    list = map(ff, oldlist)
 
-or::
+oppure::
 
    for x in sequence:
        value = ff(x)
-       ...do something with value...
+       ...fa qualcosa con value...
 
-then you can often eliminate function call overhead by rewriting
-``ff()`` to::
+in tal caso si può eliminare l'overhead dovuto alla chiamata della funzione riscrivendo
+``ff()`` come::
 
    def ffseq(seq):
        resultseq = []
        for x in seq:
-           ...do something with x computing result...
+           ...fa qualcosa con x calcolando result...
            resultseq.append(result)
        return resultseq
 
-and rewrite the two examples to ``list = ffseq(oldlist)`` and to::
+e riscrivere i due esempi come ``list = ffseq(oldlist)`` e::
 
     for value in ffseq(sequence):
-        ...do something with value...
-
-Single calls to ff(x) translate to ffseq([x])[0] with little
-penalty.  Of course this technique is not always appropriate
-and there are other variants which you can figure out.
+        ...fa qualcosa con value...
 
-You can gain some performance by explicitly storing the results of
-a function or method lookup into a local variable.  A loop like::
+Chiamate singole a ff(x) vanno riscritte come ffseq([x])[0] con
+una piccola penalizzazione in termini di tempo. Naturalmente, utilizzare
+questa tecnica non è sempre appropriato, e ci sono molte altre varianti
+da considerare.
+
+Si può guadagnare un altro po' di velocità memorizzando esplicitamente
+il risultato della ricerca del nome di una funzione o di un metodo in una 
+variabile locale. Un loop come::
 
     for key in token:
         dict[key] = dict.get(key, 0) + 1
 
-resolves dict.get every iteration.  If the method isn't going to
-change, a slightly faster implementation is::
+deve risolvere dict.get ad ogni iterazione. Se il metodo non cambia
+durante il ciclo, un'implementazione leggermente più veloce è la seguente::
 
-    dict_get = dict.get  # look up the method once
+    dict_get = dict.get  # ricerca il metodo solo una volta
     for key in token:
         dict[key] = dict_get(key, 0) + 1
 
-Default arguments can be used to determine values once, at
-compile time instead of at run time.  This can only be done for
-functions or objects which will not be changed during program
-execution, such as replacing ::
+I parametri di default possono essere usati per determinare alcuni valori
+solo una volta, a compile time piuttosto che a run time. Ciò può avvenire solo
+per funzioni o oggetti che non cambieranno durante l'esecuzione, ad esempio
+sostituendo::
 
     def degree_sin(deg):
         return math.sin(deg * math.pi / 180.0)
 
-with ::
+con ::
 
     def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):
         return sin(deg * factor)
 
-Because this trick uses default arguments for terms which should
-not be changed, it should only be used when you are not concerned
-with presenting a possibly confusing API to your users.  
+Poiché questo trucco usa i parametri di default per termini che non dovrebbero
+cambiare, andrebbe usato solo se non ci si preoccupa di presentare
+un'API confusionaria ai propri utenti.
 
 .. [- MARK -] BEGIN PART 004 of 18
 
-Core Language
+Il Core del Linguaggio
 ==================
 
-How do you set a global variable in a function?
+Come impostare una variabile globale in una funzione?
 ----------------------------------------------------------
-Did you do something like this? ::
+Si consideri qualcosa del genere::
 
-   x = 1 # make a global
+   x = 1 # variabile globale
 
    def f():
-         print x # try to print the global
+         print x # prova a stampare la variabile globale
          ...
          for j in range(100):
               if q>3:
                  x=4
 
-Any variable assigned in a function is local to that function.
-unless it is specifically declared global. Since a value is bound
-to ``x`` as the last statement of the function body, the compiler
-assumes that ``x`` is local. Consequently the ``print x``
-attempts to print an uninitialized local variable and will
-trigger a ``NameError``.
+Qualunque variabile assegnata in una funzione diventa locale a tale funzione,
+a meno che non sia esplicitamente dichiarata globale. Poiché come ultima 
+istruzione del corpo della funzione viene assegnato un valore a ``x`` ,
+il compilatore assume che ``x`` sia una variabile locale. Di conseguenza,
+la ``print x`` prova a stampare il valore di una variabile locale non
+inizializzata, e solleva un ``NameError``.
 
-The solution is to insert an explicit global declaration at the start
-of the function::
+La soluzione è inserire una dichiarazione "global" esplicita all'inizio
+della funzione::
 
    def f():
          global x
-         print x # try to print the global
+         print x # prova a stampare la variabile globale x
          ...
          for j in range(100):
               if q>3:
                  x=4
 
 
-In this case, all references to ``x`` are interpreted as references
-to the ``x`` from the module namespace.
+In tal caso, tutti i riferimenti a ``x`` vengono interpretati come riferimenti
+alla ``x`` del namespace del modulo.
 
-What are the rules for local and global variables in Python?
+Quali sono le regole per le variabili locali e globali in Python?
 --------------------------------------------------------------------------
 
-In Python, variables that are only referenced inside a function are
-implicitly global.  If a variable is assigned a new value anywhere
-within the function's body, it's assumed to be a local.  If a variable
-is ever assigned a new value inside the function, the variable is
-implicitly local, and you need to explicitly declare it as 'global'.
-
-Though a bit surprising at first, a moment's consideration explains
-this.  On one hand, requiring ``global`` for assigned variables provides
-a bar against unintended side-effects.  On the other hand, if ``global``
-was required for all global references, you'd be using ``global`` all the
-time.  You'd have to declare as global every reference to a
-builtin function or to a component of an imported module.  This
-clutter would defeat the usefulness of the ``global`` declaration for
-identifying side-effects.
-
-
-How do I share global variables across modules?
-------------------------------------------------
-
-The canonical way to share information across modules within a single
-program is to create a special module (often called config or cfg).
-Just import the config module in all modules of your application; the
-module then becomes available as a global name.  Because there is only
-one instance of each module, any changes made to the module object get
-reflected everywhere.  For example:
+In Python, le variabili che in una funzione vengono solo referenziate,
+sono implicitamente globali. Se invece a una variabile è assegnato un nuovo
+valore in qualunque punto del corpo della funzione, essa diventa implicitamente
+locale, e bisogna dichiararla esplicitamente "globale" nel caso in cui fosse
+necessario.
+
+Sebbene possa sembrare un po' sorprendente in un primo momento, qualche
+considerazione può spiegare questo comportamento. Da un lato, richiedere
+la dichiarazione ``global`` per le variabili assegnate, pone un ostacolo
+a side-effect indesiderati. D'altro canto, se ``global`` fosse richiesto  
+per tutti i riferimenti a variabili globali, bisognerebbe usarlo
+molto spesso. Bisognerebbe dichiarare globale ogni riferimento a funzioni 
+builtin o a componenti di un modulo importato. Tale confusione azzererebbe 
+l'utilità di utilizzare la dichiarazione ``global`` per identificare i side-effect.
+
+
+Come condividere variabili globali tra diversi moduli?
+------------------------------------------------------
+
+Il modo canonico per condividere informazioni tra moduli dello stesso programma
+è di creare un modulo speciale (spesso chiamato config o cfg). E' sufficiente
+importare il modulo config in tutti i moduli della propria applicazione;
+in tal caso il modulo è disponibile come un nome globale. Poiché esiste
+una sola istanza di ogni modulo, ogni cambiamento effettuato sull'oggetto
+modulo si riflette ovunque. Per esempio::
 
 config.py::
 
-    x = 0   # Default value of the 'x' configuration setting
+    x = 0   # Valore di default della variabile di configurazione "x"
 
 mod.py::
 
@@ -407,89 +410,93 @@
     import mod
     print config.x
 
-Note that using a module is also the basis for implementing the
-Singleton design pattern, for the same reason.
+C'è da notare che usare un modulo è anche la base dell'implementazione del 
+design pattern Singleton, per lo stesso motivo.
 
 
-What are the "best practices" for using import in a module?
+Quali sono le "best practices" nell'uso di import in un modulo?
 ------------------------------------------------------------------------------
 
-In general, don't use ``from modulename import *``.
-Doing so clutters the importer's namespace.  Some people avoid this idiom
-even with the few modules that were designed to be imported in this
-manner.  Modules designed in this manner include ``Tkinter``,
-and ``threading``.
-
-Import modules at the top of a file.  Doing so makes it clear what
-other modules your code requires and avoids questions of whether the
-module name is in scope.  Using one import per line makes it easy to
-add and delete module imports, but using multiple imports per line
+In generale, non usare ``from modulename import *``.
+Fare ciò ingombra il namespace del modulo che importa. Molti evitano questo
+idioma anche utilizzando i pochi moduli progettati per essere importati in
+questo modo.
+Alcuni moduli progettati in tale modo sono ad esempio ``Tkinter``,
+e ``threading``.
+
+Importare i moduli all'inizio di un file. In tal modo, è evidente quali
+moduli sono richiesti dal proprio codice, e si evitano dubbi sul fatto
+che il nome del modulo sia nello scope giusto. Usare un import per riga
+rende semplice aggiungere e rimuovere import di moduli, d'altra parte
+usare import multipli per riga
 .. [- MARK -] BEGIN PART 005 of 18
-uses less screen space.
+utilizza meno spazio a video.
 
-It's good practice if you import modules in the following order:
+È considerata buona pratica eseguire gli import nel seguente ordine:
 
-1. standard libary modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``)
-2. third-party library modules (anything installed in Python's
-   site-packages directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
-3. locally-developed modules
-
-Never use relative package imports.  If you're writing code that's 
-in the ``package.sub.m1`` module and want to import ``package.sub.m2``,
-do not just write ``import m2``, even though it's legal.
-Write ``from package.sub import m2`` instead.  Relative imports can lead to a 
-module being initialized twice, leading to confusing bugs.
-
-It is sometimes necessary to move imports to a function or class to
-avoid problems with circular imports.  Gordon McMillan says:
-
- Circular imports are fine where both modules use the "import <module>"
- form of import. They fail when the 2nd module wants to grab a name
- out of the first ("from module import name") and the import is at
- the top level. That's because names in the 1st are not yet available,
- because the first module is busy importing the 2nd.  
-
-In this case, if the second module is only used in one function, then the
-import can easily be moved into that function.  By the time the import
-is called, the first module will have finished initializing, and the
-second module can do its import.
-
-It may also be necessary to move imports out of the top level of code
-if some of the modules are platform-specific.  In that case, it may
-not even be possible to import all of the modules at the top of the
-file.  In this case, importing the correct modules in the
-corresponding platform-specific code is a good option.
-
-Only move imports into a local scope, such as inside a function
-definition, if it's necessary to solve a problem such as avoiding a
-circular import or are trying to reduce the initialization time of a
-module.  This technique is especially helpful if many of the imports
-are unnecessary depending on how the program executes.  You may also
-want to move imports into a function if the modules are only ever used
-in that function.  Note that loading a module the first time may be
-expensive because of the one time initialization of the module, but
-loading a module multiple times is virtually free, costing only a couple of
-dictionary lookups.  Even if the module name has gone out of scope,
-the module is probably available in sys.modules.
-
-If only instances of a specific class use a module, then it is
-reasonable to import the module in the class's ``__init__`` method and
-then assign the module to an instance variable so that the module is
-always available (via that instance variable) during the life of the
-object.  Note that to delay an import until the class is instantiated,
-the import must be inside a method.  Putting the import inside the
-class but outside of any method still causes the import to occur when
-the module is initialized.
+1. moduli della standard library -- es. ``sys``, ``os``, ``getopt``, ``re``
+2. moduli di librerie di terze parti (qualunque cosa installata nella directory
+   site-packages di Python) -- es. mx.DateTime, ZODB, PIL.Image, ecc.
+3. moduli sviluppati localmente
+
+Mai usare import relativi a livello di package. Se si scrive codice
+nel modulo ``package.sub.m1`` e si vuole importare ``package.sub.m2``,
+non scrivere semplicemente ``import m2``, sebbene sia perfettamente legale.
+Meglio utilizzare ``from package.sub import m2`` piuttosto.  Import relativi
+possono portare a doppie inizializzazioni di moduli, generando bug disorientanti.
+
+Talvolta è necessario spostare import in una funzione o in una classe per 
+evitare problemi con import circolari. Gordon McMillan ha detto:
+
+ Gli import circolari vanno benissimo quando entrambi i moduli usano
+ la forma "import <module>". Mentre falliscono quando il secondo modulo
+ tenta di tirar fuori un nome dal primo ("from module import name") e
+ l'import è al livello principale. Questo in quanto i nomi nel primo modulo
+ non sono ancora disponibili, in quanto esso è impegnato ad
+ importare il secondo.
+
+In tal caso, se il secondo modulo è utilizzato solo in una funzione,
+l'import può facilmente essere spostato in tale funzione. Nel momento
+in cui l'import è chiamato, il primo modulo avrà concluso la sua 
+inizializzazione, e il secondo può effettuare il suo import.
+
+A volte potrebbe anche essere necessario spostare gli import dal livello
+principale, se qualche modulo è platform-specific. In situazioni come queste, 
+potrebbe non essere neppure possibile importare tutti i moduli 
+all'inizio del file. In tal caso, importare i moduli corretti nel
+corrispondente codice dipendente dalla piattaforma è una buona scelta.
+
+Spostare gli import in uno scope locale, come in una definizione
+di funzione, solo se è necessario per risolvere un problema, come
+evitare import circolari oppure tentare di ridurre il tempo di
+inizializzazione di un modulo. Questa tecnica è particolarmente
+utile se l'utilità di molti dei moduli importati dipende da come
+procede l'esecuzione del programma. Si può decidere di spostare gli 
+import in una funzione anche se tali moduli sono utilizzati solo
+in quella funzione. Notare inoltre che il primo caricamento di un modulo
+può essere molto costoso, per il tempo di inizializzazione
+del modulo, mentre caricarlo diverse volte ha un costo virtualmente
+nullo, che si riduce a un paio di ricerche in un dizionario. Anche
+se un modulo è uscito dallo scope, probabilmente tale modulo è 
+disponibile in sys.modules.
+
+Se un modulo è utilizzato solo da istanze di una specifica classe, può
+essere ragionevole importare il modulo nel metodo ``__init__`` della classe, 
+assegnando il modulo a una variabile di istanza in modo che il modulo sia
+sempre disponibile (attraverso la variabile di istanza) durante il ciclo
+di vita dell'oggetto. Notare che per rinviare un import fino all'istanziazione
+della classe, l'import deve trovarsi all'interno di un metodo. Mettere
+l'import all'interno della classe ma fuori da qualunque metodo, causa comunque
+l'esecuzione dell'import durante l'inizializzazione del modulo.
 
-How can I pass optional or keyword parameters from one function to another?
+Come passare parametri opzionali o keyword da una funzione all'altra?
 -------------------------------------------------------------------------------
 
-Collect the arguments using the ``*`` and ``**`` specifiers in the function's
-parameter list; this gives you the positional arguments as a tuple
-and the keyword arguments as a dictionary.   You can 
-then pass these arguments when calling another function by using 
-``*`` and ``**``::
-
+Raccogliendo gli argomenti con l'uso degli specificatori ``*`` e ``**`` 
+nella lista dei parametri della funzione; in tal modo si ottengono
+gli argomenti posizionali raccolti in una tupla, e gli argomenti keyword
+in un dizionario. A questo punto, quando si chiama una funzione, si possono
+passare tali argomenti utilizzando ancora ``*`` e ``**``::
 
 	def f(x, *tup, **kwargs):
 		...
@@ -497,8 +504,9 @@
 		...
 		g(x, *tup, **kwargs)
 
-In the unlikely case that you care about Python
-versions older than 2.0, use 'apply'::
+
+Nell'improbabile caso in cui si debbano supportare versioni di Python 
+precedenti alla 2.0, si può utilizzare 'apply'::
 
 	def f(x, *tup, **kwargs):
 		...
@@ -508,53 +516,53 @@
 
 
 
-How do I write a function with output parameters (call by reference)?
+Come scrivere una funzione con parametri di output (chiamata per riferimento)?
 -----------------------------------------------------------------------------
 
-Remember that arguments are passed by assignment in Python.  Since
-assignment just creates references to objects, there's no alias
-between an argument name in the caller and callee, and so no
-call-by-reference per se.  You can achieve the desired effect in a
-number of ways.
+Bisogna ricordare che gli argomenti in Python sono passati per assegnamento.
+Poiché l'assegnamento non fa altro che creare riferimenti agli oggetti, non
+esiste un alias tra i nomi dei parametri nel chiamante e nella funzione chiamata,
+per cui non è possibile una chiamata per riferimento. Si può ottenere comunque
+l'effetto desiderato in diversi modi.
 
-1) By returning a tuple of the results::
+1) Restituendo una tupla dei risultati::
 
       def func2(a, b):
-          a = 'new-value'        # a and b are local names
-          b = b + 1              # assigned to new objects
-          return a, b            # return new values
+          a = 'new-value'        # a e b sono nomi locali
+          b = b + 1              # assegnati a nuovi oggetti
+          return a, b            # restituisce i nuovi valori
 
       x, y = 'old-value', 99
 .. [- MARK -] BEGIN PART 006 of 18
       x, y = func2(x, y)
       print x, y                 # output: new-value 100
 
-   This is almost always the clearest solution.
+   Questa è la soluzione più chiara praticamente sempre.
 
-2) By using global variables.  This isn't thread-safe, and is not
-   recommended.
+2) Utilizzando variabili globali. Non è una soluzione thread-safe, e
+   non è raccomandabile.
 
-3) By passing a mutable (changeable in-place) object::
+3) Passando un oggetto mutabile (modificabile sul posto)::
 
       def func1(a):
-          a[0] = 'new-value'     # 'a' references a mutable list
-          a[1] = a[1] + 1        # changes a shared object
+          a[0] = 'new-value'     # 'a' si riferisce a una lista mutabile
+          a[1] = a[1] + 1        # modifica un oggetto condiviso
 
       args = ['old-value', 99]
       func1(args)
       print args[0], args[1]     # output: new-value 100
 
-4) By passing in a dictionary that gets mutated::
+4) Passando un dizionario che viene modificato::
 
       def func3(args):
-          args['a'] = 'new-value'     # args is a mutable dictionary
-          args['b'] = args['b'] + 1   # change it in-place
+          args['a'] = 'new-value'     # args è un dizionario mutabile
+          args['b'] = args['b'] + 1   # lo modifica sul posto
 
       args = {'a':' old-value', 'b': 99}
       func3(args)
       print args['a'], args['b']
 
-5) Or bundle up values in a class instance::
+5) Oppure, impacchettare i valori in un'istanza di classe::
 
       class callByRef:
           def __init__(self, **args):
@@ -562,31 +570,33 @@
                   setattr(self, key, value)
 
       def func4(args):
-          args.a = 'new-value'        # args is a mutable callByRef
-          args.b = args.b + 1         # change object in-place
+          args.a = 'new-value'        # args callByRef mutabile
+          args.b = args.b + 1         # modifica l'oggetto sul posto
 
       args = callByRef(a='old-value', b=99)
       func4(args)
       print args.a, args.b
 
 
-   There's almost never a good reason to get this complicated.
+   Non esiste quasi mai una buona ragione per creare una complicazione del
+   genere.
 
-Your best choice is to return a tuple containing the multiple results.
+La scelta migliore è quella di restituire una tupla contenente tutti i risultati.
 
-How do you make a higher order function in Python?
+Come creare una funzione di ordine superiore in Python?
 ----------------------------------------------------------
-You have two choices: you can use nested scopes
-or you can use callable objects.  For example, suppose you wanted to
-define ``linear(a,b)`` which returns a function ``f(x)`` that computes the
-value ``a*x+b``.  Using nested scopes::
+Ci sono due possibilità: usare scope annidati oppure usare oggetti callable
+(richiamabili).
+Per esempio, supponiamo di voler definire una ``linear(a,b)`` che restituisce
+una funzione ``f(x)`` la quale calcola il valore ``a*x+b``.  Usando gli scope
+annidati::
 
      def linear(a,b):
          def result(x):
              return a*x + b
          return result
 
-Or using a callable object::
+Oppure, usando gli oggetti callable::
 
      class linear:
         def __init__(self, a, b):
@@ -594,22 +604,23 @@
         def __call__(self, x):
             return self.a * x + self.b
 
-In both cases::
+In entrambi i casi::
 
      taxes = linear(0.3,2)
 
-gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.
+produce un oggetto callable in cui taxes(10e6) == 0.3 * 10e6 + 2.
 
-The callable object approach has the disadvantage that it is a bit
-slower and results in slightly longer code.  However, note that a
-collection of callables can share their signature via inheritance::
+L'approccio con oggetti callable ha lo svantaggio di essere un po'
+più lento e di risultare in codice leggermente più lungo.
+Comunque, c'è da notare che diversi callable possono condividere
+la stessa signature tramite l'ereditarietà::
 
       class exponential(linear):
-         # __init__ inherited
+         # __init__ ereditato
          def __call__(self, x):
              return self.a * (x ** self.b)
 
-Object can encapsulate state for several methods::
+Gli oggetti possono incapsulare lo stato per diversi metodi::
 
     class counter:
         value = 0
@@ -620,41 +631,40 @@
     count = counter()
     inc, dec, reset = count.up, count.down, count.set
 
-Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
-same counting variable.
-
+Qui ``inc()``, ``dec()`` and ``reset()`` si comportano come funzioni che 
+condividono la stessa variabile di conteggio.
 
-How do I copy an object in Python?
+Come copiare un oggetto in Python?
 ------------------------------------------
 .. [- MARK -] BEGIN PART 007 of 18
 
-In general, try copy.copy() or copy.deepcopy() for the general case. Not all
-objects can be copied, but most can.  
+In generale, si può provare copy.copy() o copy.deepcopy() nel caso generale.
+Non tutti gli oggetti possono essere copiati, ma la maggior parte si.
 
-Some objects can be copied more easily.
-Dictionaries have a ``copy()`` method::
+Alcuni oggetti possono essere copiati in modo più semplice.
+I dizionari hanno un metodo ``copy()``::
 
    newdict = olddict.copy()
 
-Sequences can be copied by slicing::
+Le sequenze possono essere copiate tramite slicing::
 
    new_l = l[:]
 
 
-How can I find the methods or attributes of an object?
+Come trovare i metodi o gli attributi di un oggetto?
 -------------------------------------------------------------- 
-For an instance x of a user-defined class, ``dir(x)`` returns an
-alphabetized list of the names containing the instance attributes and
-methods and attributes defined by its class.
+Per un'istanza x di una classe definita dall'utente, ``dir(x)`` restituisce
+una lista in ordine alfabetico dei nomi contenti gli attributi dell'istanza
+e metodi e attributi definiti dalla sua classe.
 
 
-How can my code discover the name of an object?
+Come si può trovare da codice il nome di un oggetto?
 -------------------------------------------------------
 
-Generally speaking, it can't, because objects don't really have
-names. Essentially, assignment always binds a name to a value; The
-same is true of ``def`` and ``class`` statements, but in that case the
-value is a callable. Consider the following code::
+In generale, non si può, in quanto gli oggetti non hanno realmente un nome.
+Essenzialmente, l'assegnamento lega sempre un nome a un valore; lo stesso
+vale per le istruzioni ``def`` e ``class``, ma in tal caso il valore
+è un oggetto callable. Consideriamo il seguente codice::
 
     class A:
         pass
@@ -668,50 +678,46 @@
     print a
     <__main__.A instance at 016D07CC>
 
+Discutibilmente, la classe ha un nome: anche se essa è legata a due nomi e
+invocata tramite il nome B, l'istanza generata è comunque riportata 
+come un'istanza di classe A. Tuttavia, è impossibile dire se il nome
+dell'istanza è a o b, poiché entrambi i nomi sono legati allo stesso valore.
 
-Arguably the class has a name: even though it is bound to two names
-and invoked through the name B the created instance is still reported
-as an instance of class A. However, it is impossible to say whether
-the instance's name is a or b, since both names are bound to the same
-value.
-
-Generally speaking it should not be necessary for your code to "know
-the names" of particular values. Unless you are deliberately writing
-introspective programs, this is usually an indication that a change of
-approach might be beneficial.
+In generale, il codice non dovrebbe mai avere la necessità di "conoscere il
+nome" di particolari valori. Normalmente, questa necessità indica il bisogno
+di un altro tipo di approccio, a meno che non si stia intenzionalmente
+scrivendo un programma introspettivo.
 
-In comp.lang.python, Fredrik Lundh once gave an excellent analogy in
-answer to this question:
+Su comp.lang.python, Fredrik Lundh ha fatto un'eccellente analogia in risposta
+a questa domanda::
 
-   The same way as you get the name of that cat you found on your
-   porch: the cat (object) itself cannot tell you its name, and it
-   doesn't really care -- so the only way to find out what it's called
-   is to ask all your neighbours (namespaces) if it's their cat
-   (object)...
+   Allo stesso modo in cui ottieni il nome del gatto che hai trovato
+   in veranda: il gatto (oggetto) non può dirti il suo nome, e in realtà
+   non è molto importante -- per cui, l'unico modo per trovarne il nome
+   è chiedere a tutti i vicini (namespace) se il gatto (oggetto) è loro...
 
-   ....and don't be surprised if you'll find that it's known by many
-   names, or no name at all!
+   ....e non essere sopreso se trovi che esso è conosciuto con molti
+   nomi, oppure con nessun nome!
 
 
 
-Is there an equivalent of C's "?:" ternary operator?
+Esiste un equivalente dell'operatore ternario "?:" del C?
 ----------------------------------------------------------------------
-No.  In many cases you can mimic a?b:c with "a and b or
-c", but there's a flaw: if b is zero (or empty, or None -- anything
-that tests false) then c will be selected instead.  In many cases you
-can prove by looking at the code that this can't happen (e.g. because
-b is a constant or has a type that can never be false), but in general
-this can be a problem.
-
-Tim Peters (who wishes it was Steve Majewski) suggested the following
-solution: (a and [b] or [c])[0].  Because [b] is a singleton list it
-is never false, so the wrong path is never taken; then applying [0] to
-the whole thing gets the b or c that you really wanted.  Ugly, but it
-gets you there in the rare cases where it is really inconvenient to
-rewrite your code using 'if'.
+No. In molti casi si può imitare a?b:c con "a and b or c", ma c'è un problema:
+se b è zero (o vuoto, o None -- qualunque cosa che viene valutata come False),
+verrà selezionato c. In molti casi, è possibile provare che ciò non può accadere
+semplicemente guardando il codice (es. perché b è una costante o è di un tipo
+che non viene mai valutato come False), ma in generale può nascere un problema.
+
+Tim Peters (ma c'è chi vuole sia stato Steve Majewski) ha suggerito la 
+seguente soluzione: (a and [b] or [c])[0]. Poiché [b] è una lista singleton,
+non sarà mai False, per cui il percorso errato non verrà mai scelto; quindi
+applicando [0] al risultato si ottiene la b o la c desiderata. Sporco, ma
+utile nei rari casi in cui è realmente inopportuno riscrivere il proprio
+codice usando 'if'.
 
-The best course is usually to write a simple ``if...else`` statement.
-Another solution is to implement the "?:" operator as a function::
+La strada migliore è normalmente scrivere un semplice ``if...else``.
+Un'altra soluzione può essere implementare l'operatore "?:" con una funzione::
 
     def q(cond,on_true,on_false):
         if cond: 
@@ -721,39 +727,39 @@
             if not isfunction(on_false): return on_false 
             else: return apply(on_false)
 
-In most cases you'll pass b and c directly: ``q(a,b,c)``.  To avoid
-evaluating b or c when they shouldn't be, encapsulate them within a
-lambda function, e.g.: ``q(a,lambda: b, lambda: c)``.  
+Nella maggior parte dei casi, b e c verranno passati direttamente: ``q(a,b,c)``.  
+Per evitare di valutare b o c quando non dovrebbero esserlo, possono
+essere incapsulate in funzioni lambda, es. ``q(a,lambda: b, lambda: c)``.  
 
-It has been asked *why* Python has no if-then-else expression.
-There are several answers: many languages do
+Molti chiedono *perché* Python non abbia un'espressione if-then-else (NdT espressione, non istruzione!).
+Ci sono parecchie risposte: molti linguaggi fanno benissimo anche senza;
 .. [- MARK -] BEGIN PART 008 of 18
-just fine without one; it can easily lead to less readable code;
-no sufficiently "Pythonic" syntax has been discovered; a search
-of the standard library found remarkably few places where using an
-if-then-else expression would make the code more understandable.
-
-In 2002, `PEP 308 <../../peps/pep-0308.html>`_ was
-written proposing several possible syntaxes and the community was
-asked to vote on the issue.  The vote was inconclusive.  Most people
-liked one of the syntaxes, but also hated other syntaxes; many votes
-implied that people preferred no ternary operator 
-rather than having a syntax they hated.
+essa può facilmente portare a codice meno leggibile; non è stata
+trovata una sintassi abbastanza "Pythonica"; una ricerca nella libreria
+standard ha trovato ben pochi luoghi dove l'uso di un'espressione
+if-then-else avrebbe reso il codice più comprensibile.
+
+Nel 2002 è stata scritta la `PEP 308 <../../peps/pep-0308.html>`_ 
+con diverse proposte di sintassi, ed è stata messa al voto della comunità.
+Il voto è stato inconcludente. A molte persone piaceva una delle sintassi,
+ma allo stesso tempo odiavano le altre; molti voti hanno denotato
+che le persone preferivano non avere un operatore ternario piuttosto
+che avere una sintassi odiosa.
 
-Is it possible to write obfuscated one-liners in Python?
+È possibile scrivere one-liner offuscati in Python?
 ----------------------------------------------------------------
-Yes.  Usually this is done by nesting `lambda` within `lambda`.  
-See the following three examples, due to Ulf Bartelt::
+Sì. Di solito ciò si ottiene annidando `lambda` all'interno di altre `lambda`.
+Si guardino i tre esempi seguenti, dovuti a Ulf Bartelt::
 
-        # Primes < 1000
+        # Primi < 1000
         print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
         map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
 
-        # First 10 Fibonacci numbers
+        # Primi 10 numeri di Fibonacci
         print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
         range(10))
 
-        # Mandelbrot set
+        # Insieme di Mandelbrot
         print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
         Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
         Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
@@ -761,32 +767,31 @@
         >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
         64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
         ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
-        #    \___ ___  \___ ___  |   |   |__ lines on screen
-        #        V          V      |   |______ columns on screen
-        #        |          |      |__________ maximum of "iterations"
-        #        |          |_________________ range on y axis
-        #        |____________________________ range on x axis
+        #    \___ ___  \___ ___  |   |   |__ righe sullo schermo
+        #        V          V      |   |______ colonne sullo schermo
+        #        |          |      |__________ n.massimo di "iterazioni"
+        #        |          |_________________ intervallo sull'asse y
+        #        |____________________________ intervallo sull'asse x
 
-Don't try this at home, kids!
+Ragazzi, "Don't try this at home"!
 
 
-Numbers and strings
+Numeri e stringhe
 ==========================
 
-How do I specify hexadecimal and octal integers?
+Come si specificano interi esadecimali e ottali?
 --------------------------------------------------------
-
-To specify an octal digit, precede the octal value with a zero.  For
-example, to set the variable "a" to the octal value "10" (8 in
-decimal), type::
+Per specificare un numero ottale, basta preporre uno zero al suo valore ottale.
+Per esempio, per impostare la variabile "a" al valore ottale "10" (8 in decimale), 
+basta scrivere::
 
     >>> a = 010
     >>> a
     8
 
-Hexadecimal is just as easy.  Simply precede the hexadecimal number with a
-zero, and then a lower or uppercase "x".  Hexadecimal digits can be specified
-in lower or uppercase.  For example, in the Python interpreter::
+Per l'esadecimale è altrettanto semplice. E'sufficiente preporre uno zero e una
+"x" minuscola o maiuscola al numero esadecimale. Le cifre esadecimali possono
+essere specificate in minuscolo o in maiuscolo. Per esempio, nell'interprete Python::
 
     >>> a = 0xa5
     >>> a
@@ -796,67 +801,68 @@
     178
 
 
-Why does -22 / 10 return -3?
+Perché -22 / 10 restituisce -3?
 ----------------------------------
 
-It's primarily driven by the desire that ``i%j`` have the same sign as
-``j``.  If you want that, and also want::
+Questo comportamento è principalmente dovuto al desiderio che ``i%j`` abbia lo 
+stesso segno di ``j``.  Se si vuole ciò, e se si vuole anche che:
 
     i == (i/j)*j + (i%j)
 
-then integer division has to return the floor.  C also requres that identity
-to hold, and then compilers that truncate ``i/j`` need to make ``i%j`` have
-the same sign as ``i``.
-
-There are few real use cases for ``i%j`` when ``j`` is negative.  When ``j``
-is positive, there are many, and in virtually all of them it's more useful
-for ``i%j`` to be ``>= 0``.  If the clock says 10 now, what did it say 200
-hours ago?  ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug
-waiting to bite.
+allora la divisione intera deve restituire il "floor". Anche il C mantiene
+questa identità, quindi i compilatori che troncano ``i/j`` devono fare in modo
+che ``i%j`` abbia lo stesso segno di ``i``.
+
+Ci sono pochi casi d'uso reali per ``i%j`` quando ``j`` è negativo. Quando
+``j`` è positivo, ce ne sono molti, e in praticamente tutti è più utile
+che ``i%j`` sia ``>= 0``. Se l'orologio segna le 10 adesso, che ore erano 200 
+ore fa? ``-190 % 12 == 2`` è utile, ``-190 % 12 == -10`` è un bug pronto a esplodere.
 
-How do I convert a string to a number?
+Come convertire una stringa in un numero?
 ----------------------------------------------
 
-For integers, use the built-in ``int()`` type constructor,
-e.g. int('144') == 144.  Similarly, ``float()`` converts to
-floating-point, e.g. ``float('144') == 144.0``.
-
-By default, these interpret the number as decimal, so that
-``int('0144') == 144`` and ``int('0x144')`` raises
-``ValueError``. ``int(string, base)`` takes the base to convert from
-as a second optional argument, so ``int('0x144', 16) == 324``.  If the
-base is specified as 0, the number is interpreted using Python's
-rules: a leading '0' indicates octal, and '0x' indicates a hex number.
+Per gli interi, si usa il costruttore di tipo built-in ``int()``,
+es. int('144') == 144. In modo simile, ``float()`` converte in
+valori floating-point, es. ``float('144') == 144.0``.
+
+Di default, queste funzioni interpretano il numero come un valore decimale,
+in modo che ``int('0144') == 144`` e ``int('0x144')`` sollevano un
+``ValueError``. ``int(string, base)`` accetta la base da cui convertire
+come secondo argomento opzionale, per cui ``int('0x144', 16) == 324``. 
+Se come base è specificato 0, il numero è interpretato usando le regole
+di Python: uno 0 precedente indica un numero ottale, e '0x' indica un 
+numero esadecimale.
 
 .. [- MARK -] BEGIN PART 009 of 18
-Do not use the built-in function ``eval()`` if all you need is to
-convert strings to numbers.  ``eval()`` will be significantly slower
-and it presents a security risk: someone could pass you a Python
-expression that might have unwanted side effects.  For example,
-someone could pass ``__import__('os').system("rm -rf $HOME")`` which
-would erase your home directory.
-
-``eval()`` also has the effect of interpreting numbers as Python
-expressions, so that e.g. eval('09') gives a syntax error because Python
-regards numbers starting with '0' as octal (base 8).
+Non usare la funzione built-in ``eval()`` se la necessità è solo quella
+di convertire stringhe in numeri. ``eval()`` è parecchio più lenta,
+e presenta un rischio di sicurezza: qualcuno potrebbe passare 
+un'espressione Python che potrebbe avere effetti secondari indesiderati.
+Per esempio, se qualcuno passasse ``__import__('os').system("rm -rf $HOME")`` 
+eliminerebbe la home directory.
+
+``eval()`` ha anche l'effetto di interpretare i numeri come espressioni Python,
+in modo che per esempio eval('09') restituisce un errore di sintassi
+in quanto Python considera i numeri che cominciano con '0' come ottali (base 8).
 
 
-How do I convert a number to a string?
+Come convertire un numero in una stringa?
 ----------------------------------------------
 
-To convert, e.g., the number 144 to the string '144', use the built-in
-function ``str()``.  If you want a hexadecimal or octal
-representation, use the built-in functions ``hex()`` or ``oct()``.
-For fancy formatting, use `the % operator <../../doc/lib/typesseq-strings.html>`_ on strings, e.g. ``"%04d" % 144``
-yields '0144' and ``"%.3f" % (1/3.0)`` yields '0.333'.  See the library
-reference manual for details.  
+Per convertire, per esempio, il numero 144 nella stringa '144', basta
+usare la funzione built-in ``str()``. Se si vuole una rappresentazione
+esadecimale oppure ottale, si usano le funzioni built-in ``hex()`` or ``oct()``.
+Per formattazioni particolari, si usa `l'operatore % <../../doc/lib/typesseq-strings.html>`_ 
+sulle stringhe, es. ``"%04d" % 144`` produce '0144' and ``"%.3f" % (1/3.0)`` 
+produce '0.333'.  Per i dettagli, consultare il reference manual della libreria
+standard.
 
-How do I modify a string in place?
+Come modificare una stringa sul posto?
 ------------------------------------------
 
-You can't, because strings are immutable.  If you need an object with
-this ability, try converting the string to a list or use the array
-module::
+Non è possibile, in quanto le stringhe sono immutabili. Se si necessita
+di un oggetto con questa capacità, si può provare a convertire la stringa
+in una lista o usare il modulo array::
 
     >>> s = "Hello, world"
     >>> a = list(s)
@@ -877,15 +883,15 @@
 
 
 
-How do I use strings to call functions/methods?
+Come usare stringhe per chiamare funzioni/metodi?
 ----------------------------------------------------------
 
-There are various techniques.
+Ci sono varie tecniche.
 
-* The best is to use a dictionary that maps strings to functions.  The
-  primary advantage of this technique is that the strings do not need
-  to match the names of the functions.  This is also the primary
-  technique used to emulate a case construct::
+* La migliore è di usare un dizionario che mappi da stringhe a funzioni.
+  Il principale vantaggio di questa tecnica è che non c'è la necessità
+  che le stringhe corrispondano ai nomi delle funzioni. Questa è
+  anche la principale tecnica usata per emulare il costrutto case::
 
     def a():
         pass
@@ -893,20 +899,20 @@
     def b():
         pass
 
-    dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs
+    dispatch = {'go': a, 'stop': b}  # Notare la mancanza delle parentesi per le funzioni
 
-    dispatch[get_input()]()  # Note trailing parens to call function
+    dispatch[get_input()]()  # Notare le parentesi finali per chiamare la funzione
 
-* Use the built-in function ``getattr()``::
+* Usare la funzione built-in ``getattr()``::
 
     import foo
     getattr(foo, 'bar')()
 
-  Note that getattr() works on any object, including classes, class
-  instances, modules, and so on.
+  Notare che getattr() funziona su qualunque oggetto, incluse classi,
+  istanze di classi, moduli, e così via.  
 
-  This is used in several places in the standard library, like
-  this::
+  Questo costrutto è usato in diversi posti nella libreria standard, in
+  questo modo::
 
     class Foo:
         def do_foo(self):
@@ -919,7 +925,7 @@
      f()
 
 
-* Use ``locals()`` or ``eval()`` to resolve the function name::
+* Usare ``locals()`` o ``eval()`` per risolvere il nome della funzione::
 
     def myFunc():
         print "hello"
@@ -933,18 +939,19 @@
     f = eval(fname)
     f()
 
-  Note: Using ``eval()`` is slow and dangerous. If you don't have absolute control
-  over the contents of the string, someone could pass a string that 
-  resulted in an arbitrary function being executed.
+  Nota: Usare ``eval()`` è lento e pericoloso. Se non si ha il controllo assoluto
+  sul contenuto della stringa, qualcuno può passare una stringa che può avere come
+  risultato l'esecuzione di una funzione arbitraria.
 
-Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
+Esiste un equivalente del chomp() di Perl per rimuovere i newline finali dalle stringhe?
 --------------------------------------------------------------------------------------------
 
-Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove
-all occurances of any line terminator from the end of the string ``S``
-without removing other trailing whitespace.  If the string ``S``
-represents more than one line, with several empty lines at the end,
-the line terminators for all the blank lines will be removed::
+A cominciare da Python 2.2, si può usare ``S.rstrip("\r\n")`` per 
+rimuovere tutte le occorrenze di qualsiasi terminatore di linea dalla 
+fine della stringa ``S``, senza rimuovere nessun'altro carattere
+di spaziatura. Se la stringa ``S`` rappresenta più di una riga, con
+diverse righe vuote alla fine, saranno rimosi tutti i terminatori
+di tutte le righe vuote::
 
     >>> lines = ("line 1 \r\n"
     ...          "\r\n"
@@ -952,138 +959,143 @@
     >>> lines.rstrip("\n\r")
     "line 1 "
 
-Since this is typically only desired when reading text one line at a
-time, using ``S.rstrip()`` this way works well.
+Poiché tipicamente si vuole ciò solo quando si legge del testo
+una riga alla volta, usare ``S.rstrip()`` in questo modo funziona bene.
 
-For older versions of Python, There are two partial substitutes:
+Per versioni più vecchie di Python, ci sono due parziali sostituti::
 
-- If you want to remove all trailing whitespace, use the ``rstrip()``
-  method of string objects.  This removes all trailing whitespace, not
-  just a single newline.
+- Per rimuovere tutti i caratteri di spaziatura, utilizzare il metodo
+  ``rstrip()`` degli oggetti stringa. Ciò rimuove tutti gli spazi
+  finali, non solo un singolo newline.
 
-- Otherwise, if there is only one line in the string ``S``, use
+- Oppure, se la stringa ``S`` è composta da una sola riga, si può usare
   ``S.splitlines()[0]``.
 
 
-Is there a scanf() or sscanf() equivalent?
+Esiste un equivalente di scanf() o sscanf()?
 --------------------------------------------------
-Not as such.
+Niente di equivalente.
 
-For simple input parsing, the easiest approach is usually to split the
-line into whitespace-delimited words using the ``split()`` method of
-string objects and then convert decimal strings to numeric values using
-``int()`` or ``float()``.  ``split()`` supports an optional "sep"
-parameter which is useful if the line uses something other than
-whitespace as a separator.
+Per il parsing di input semplici, l'approccio più facile è di solito
+fare lo split della riga in parole delimitate da spazi, usando il metodo 
+``split()`` dell'oggetto stringa, e successivamente convertire le stringhe
+decimali in valori numerici usando ``int()`` o ``float()``. ``split()``
+supporta un parametro opzionale "sep", che è utile se la riga
+utilizza un separatore diverso da un carattere di spaziatura.
 
-For more complicated input parsing, regular expressions 
-more powerful than C's ``sscanf()`` and better suited for the task.
+Per il parsing di input più complessi, le espressioni regolari sono più
+potenti e adatte allo scopo della ``sscanf()`` del C.
 
 
-What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?
+Cosa significa 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)'?
 -----------------------------------------------------------------------------------------------------
-This error indicates that your Python installation can handle
-only 7-bit ASCII strings.  There are a couple ways to fix or
-work around the problem.
-
-If your programs must handle data in arbitary character set encodings,
-the environment the application runs in will generally identify the
-encoding of the data it is handing you.  You need to convert the input
-to Unicode data using that encoding.  For example, a program that
-handles email or web input will typically find character set encoding
-information in Content-Type headers.  This can then be used to
-properly convert input data to Unicode. Assuming the string referred
-to by ``value`` is encoded as UTF-8::
+Questo errore indica che l'installazione corrente di Python può gestire
+solo stringe ASCII a 7 bit. Ci sono un paio di modi per risolvere o 
+aggirare il problema.
+
+Se il proprio programma ha la necessità di gestire dati in set di
+caratteri con codifica arbitraria, l'ambiente in cui gira l'applicazione
+generalmente conosce l'encoding dei dati che si gestiscono.
+Bisogna convertire l'input in formato Unicode utilizzando tale
+codifica. Per esempio, un programma che gestisce email oppure
+input dal web, normalmente troverà le informazioni sull'encoding
+negli headers Content-Type. Questa informazione può quindi essere 
+utilizzata per convertire i dati di input in Unicode nel modo corretto.
+Assumendo che la stringa a cui si riferisce ``value`` sia codificata come
+UTF-8::
 
     value = unicode(value, "utf-8")
 
-will return a Unicode object.  If the data is not correctly encoded as
-UTF-8, the above call will raise a ``UnicodeError`` exception.
+restituisce un oggetto Unicode. Se il valore non è codificato correttamente
+come UTF-8, la chiamata precedente solleverà un'eccezione di tipo ``UnicodeError``.
 
-If you only want strings coverted to Unicode which have non-ASCII
-data, you can try converting them first assuming an ASCII encoding,
-and then generate Unicode objects if that fails::
+Se si vuole convertire in Unicode solo stringhe che hanno dati non ASCII,
+si può provare a convertirle prima in una codifica ASCII e poi generare
+oggetti Unicode se tale conversione fallisce::
 
     try:
         x = unicode(value, "ascii")
     except UnicodeError:
         value = unicode(value, "utf-8")
     else:
-        # value was valid ASCII data
+        # value è una stringa ASCII valida
         pass
 
-It's possible to set a default encoding in a file called ``sitecustomize.py``
-that's part of the Python library.  However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail.
-
-Note that on Windows, there is an encoding known as "mbcs", which uses
-an encoding specific to your current locale.  In many cases, and
-particularly when working with COM, this may be an appropriate default
-encoding to use.
+E'possibile impostare una codifica di default in un file di nome
+``sitecustomize.py``, parte della libreria Python. Tuttavia, ciò
+non è raccomandato in quanto cambiare l'encoding di default dell'intera
+installazione di Python potrebbe causare errori sui moduli di
+terze parti.
+
+Si noti che su Windows esiste una codifica conosciuta come "mbcs", la quale
+utilizza un encoding specifico per il locale corrente. In molti casi, ed in
+particolare quando si lavora con COM, questa dovrebbe essere la codifica
+di default più appropriata.
 
 
-Sequences (Tuples/Lists)
+Sequenze (Tuple/Liste)
 =================================
 
-How do I convert between tuples and lists?
+Come si converte tra tuple e liste?
 ------------------------------------------------ 
 
-The function ``tuple(seq)`` converts any sequence (actually, any
-iterable) into a tuple with the same items in the same order.
+La funzione ``tuple(seq)`` converte qualunque sequenza (in realtà,
+qualunque iterabile) in una tupla con gli stessi elementi nello stesso ordine.
 
 .. [- MARK -] BEGIN PART 011 of 18
-For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
-yields ``('a', 'b', 'c')``.  If the argument is
-a tuple, it does not make a copy but returns the same object, so
-it is cheap to call ``tuple()`` when you aren't sure that an object
-is already a tuple.
-
-The function ``list(seq)`` converts any sequence or iterable into a list with
-the same items in the same order.
-For example, ``list((1, 2, 3))`` yields ``[1, 2, 3]`` and ``list('abc')``
-yields ``['a', 'b', 'c']``.  If the argument is a list,
-it makes a copy just like ``seq[:]`` would.
+Per esempio, ``tuple([1, 2, 3])`` produce ``(1, 2, 3)`` e ``tuple('abc')``
+produce ``('a', 'b', 'c')``.  Se l'argomento è una tupla, non verrà
+creata una copia, ma restituito lo stesso oggetto, per cui chiamare
+``tuple()`` è un'operazione economica anche quando non si è sicuri
+che l'oggetto non sia già una tupla.
+
+La funzione ``list(seq)`` converte qualunque sequenza o iterabile in una lista
+con gli stessi elementi nello stesso ordine. Per esempio, ``list((1, 2, 3))`` 
+produce ``[1, 2, 3]`` e ``list('abc')`` produce ``['a', 'b', 'c']``.  
+Se l'argomento è una lista, essa crea una copia esattamente come farebbe ``seq[:]``.
 
-What's a negative index? 
+Cos'è un indice negativo?
 --------------------------------------------------------------------
-Python sequences are indexed with positive numbers and
-negative numbers.  For positive numbers 0 is the first index
-1 is the second index and so forth.  For negative indices -1
-is the last index and -2 is the pentultimate (next to last) index
-and so forth.  Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.
-
-Using negative indices can be very convenient.  For example ``S[:-1]``
-is all of the string except for its last character, which is useful
-for removing the trailing newline from a string.
+Le sequenze Python possono essere indicizzate con numeri positivi
+oppure negativi. Per i numeri positivi, 0 è il primo indice, 1
+il secondo e così via. Per gli indici negativi, -1 è l'ultimo
+indice, -2 il penultimo e così via. Si può pensare che ``seq[-n]`` 
+sia equivalente a ``seq[len(seq)-n]``.
+
+Usare indici negativi può essere molto conveniente. Per esempio ``S[:-1]``
+è tutta la stringa tranne l'ultimo carattere, il che può essere utile
+per rimuovere il newline finale da una stringa.
 
 
-How do I iterate over a sequence in reverse order?
+Come si itera su una sequenza in ordine inverso?
 ---------------------------------------------------------
-If it is a list, the fastest solution is ::
+Se la sequenza è una lista, la soluzione più veloce è:
 
         list.reverse()
         try:
             for x in list:
-                "do something with x"
+                "fa qualcosa con x"
         finally:
             list.reverse()
 
-This has the disadvantage that while you are in the loop, the list
-is temporarily reversed.  If you don't like this, you can make a copy.
-This appears expensive but is actually faster than other solutions::
+
+Questa soluzione ha lo svantaggio che, durante il ciclo, la lista
+è temporaneamente invertita. Se questo non piace, si può effettuare
+una copia. Può sembrare costoso, ma in realtà è più veloce di altre soluzioni::
 
         rev = list[:]
         rev.reverse()
         for x in rev:
-                <do something with x>
+                <fa qualcosa con x>
 
-If it's not a list, a more general but slower solution is::
+Se non si tratta di una lista, una soluzione più generale ma più lenta è::
 
         for i in range(len(sequence)-1, -1, -1):
                 x = sequence[i]
-                <do something with x>
+                <fa qualcosa con x>
 
-A more elegant solution, is to define a class which acts as a sequence
-and yields the elements in reverse order (solution due to Steve
+Una soluzione più elegante è definire una classe che si comporta come
+una sequenza e produce gli elementi in ordine inverso (soluzione di Steve
 Majewski)::
 
         class Rev:
@@ -1094,27 +1106,29 @@
                 def __getitem__(self, i):
                         return self.forw[-(i + 1)]
 
-You can now simply write::
+A questo punto basta scrivere::
 
         for x in Rev(list):
-                <do something with x>
+                <fa qualcosa con x>
 
-Unfortunately, this solution is slowest of all, due to the method
-call overhead.
+Sfortunatamente, questa è la soluzione più lenta, per l'overhead
+dovuto alla chiamata del metodo.
 
-With Python 2.3, you can use an extended slice syntax::
+Con Python 2.4, si può utilizzare una sintassi estesa per le slice::
 
         for x in sequence[::-1]:
-               <do something with x>
+               <fa qualcosa con x>
 
-How do you remove duplicates from a list?
+Come rimuovere i duplicati da una lista?
 -------------------------------------------------
-See the Python Cookbook for a long discussion of many ways to do this:
+Si consulti il Python Cookbook per una lunga discussione sui vari
+metodi per fare ciò:
 
     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
 
-If you don't mind reordering the list, sort it and then scan from the
-end of the list, deleting duplicates as you go::
+Se non è un problema riordinare la lista, si può ordinarla e 
+successivamente analizzarla dalla fine, eliminando i duplicati
+man mano::
 
    if List:
       List.sort()
@@ -1123,112 +1137,114 @@
           if last==List[i]: del List[i]
           else: last=List[i]
 
-If all elements of the list may be used as
-dictionary keys (i.e. they are all hashable)
-this is often faster ::
+Se tutti gli elementi della lista possono essere utilizzati
+come chiavi di dizionario (dunque se essi sono tutti hashable),
+la seguente soluzione è spesso più veloce::
 
    d = {}
    for x in List: d[x]=x
    List = d.values()
 
 .. [- MARK -] BEGIN PART 012 of 18
-How do you make an array in Python?
+Come si crea un array in Python?
 ----------------------------------------------------
-Use a list::
+Usando una lista::
 
 	["this", 1, "is", "an", "array"]
 
-Lists are equivalent to C or Pascal arrays in their time complexity;
-the primary difference is that a Python list can contain objects of
-many different types.
-
-The ``array`` module also provides methods for creating arrays of
-fixed types with compact representations, but they are slower to index
-than lists.  Also note that the Numeric extensions and others define
-array-like structures with various characteristics as well.
+Le liste sono equivalenti agli array di C o Pascal in quanto a complessità
+temporale; la differenza principale è che le liste Python possono contenere
+oggetti di diversi tipi.
+
+Il modulo ``array`` fornisce anche metodi per creare array di tipi fissi
+con rappresentazioni compatte, ma l'indicizzazione su di essi è più
+lenta rispetto alle liste. Bisogna notare anche che l'estensione Numeric,
+e altre, definiscono strutture simili agli array con caratteristiche varie.
 
-To get Lisp-style linked lists, you can emulate cons cells using tuples::
+Per ottenere liste collegate "alla Lisp", si possono emulare le cons cells
+utilizzando delle tuple::
 
     lisp_list = ("like",  ("this",  ("example", None) ) )
 
-If mutability is desired, you could use lists instead of tuples.  Here
-the analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr
-is ``lisp_list[1]``.  Only do this if you're sure you really need to,
-because it's usually a lot slower than using Python lists.
+Se si desidera che l'oggetto sia mutabile, si possono utilizzare liste
+piuttosto che tuple. In tal caso, l'analogo del car lisp è ``lisp_list[0]``,
+mentre l'analogo del cdr è ``lisp_list[1]``. Bisogna utilizzare tale 
+costrutto solo se si è sicuri che è realmente necessario, in quanto
+esso è normalmente molto più lento rispetto alle liste Python.
 
-How do I create a multidimensional list?
+Come creare una lista multidimensionale?
 ---------------------------------------------------------------
-You probably tried to make a multidimensional array like this::
+Spesso si tenta di creare array multidimensionali in questo modo::
 
    A = [[None] * 2] * 3
 
-This looks correct if you print it::
+Il che sembra corretto se stampato::
 
 	>>> A
 	[[None, None], [None, None], [None, None]]
 
-But when you assign a value, it shows up in multiple places:
+Ma se si assegna un valore, tale valore appare più volte::
 
 	>>> A[0][0] = 5
 	>>> A
 	[[5, None], [5, None], [5, None]]
 
-The reason is that replicating a list with ``*`` doesn't create copies, it only creates references to the existing objects.  The ``*3`` 
-creates a list containing 3 references to the same list of length
-two.  Changes to one row will show in all rows, which is almost certainly 
-not what you want.  
+Il motivo è che la replica di una lista con ``*`` non crea copie, ma solo riferimenti agli oggetti esistenti.
+Il ``*3`` crea una lista contenente 3 riferimenti alla stessa lista di lunghezza due. Le modifiche
+a una riga appariranno in tutte le righe, il che quasi certamente non è ciò che si vuole.
 
-The suggested approach is to create a list of the desired length first
-and then fill in each element with a newly created list::
+L'approccio suggerito è di creare prima una lista della lunghezza desiderata,
+e successivamente riempire ogni elemento con una nuova lista::
 
    A = [None]*3
    for i in range(3):
         A[i] = [None] * 2
 
-This generates a list containing 3 different lists of length two.
-You can also use a list comprehension::
+Questo genera una lista contenente 3 diverse liste di lunghezza due.
+Si può anche utilizzare una list comprehension::
 
    w,h = 2,3
    A = [ [None]*w for i in range(h) ]
 
-Or, you can use an extension that provides a matrix datatype; `Numeric
-Python <http://www.pfdubois.com/numpy/>`_ is the best known.
+Oppure, si può utilizzare un'estensione che fornisce un tipo di dato matrice: `Numeric
+Python <http://www.pfdubois.com/numpy/>`_ è la più conosciuta.
 
 
-How do I apply a method to a sequence of objects?
+Come si esegue un metodo su una sequenza di oggetti?
 --------------------------------------------------------------------------
 
-Use a list comprehension::
+Usando una list comprehension::
 
 	result = [obj.method() for obj in List]	
 
-More generically, you can try the following function::
+Più in generale, si può provare la seguente funzione::
 
   def method_map(objects, method, arguments):
-       """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
+       """method_map([a,b], "meth", (1,2)) da [a.meth(1,2), b.meth(1,2)]"""
        nobjects = len(objects)
        methods = map(getattr, objects, [method]*nobjects)
        return map(apply, methods, [arguments]*nobjects)
 
 
-Dictionaries
+Dizionari
 ==================
 
-How can I get a dictionary to display its keys in a consistent order?
+Come ottenere che un dizionario mostri le sue chiavi in un ordine consistente?
 -----------------------------------------------------------------------------
 
-You can't.  Dictionaries store their keys in an unpredictable order,
-so the display order of a dictionary's elements will be similarly
-unpredictable.
-
-This can be frustrating if you want to save a printable version to a 
-file, make some changes and then compare it with some other printed
-dictionary.  In this case, use the ``pprint`` module to pretty-print 
-the dictionary; the items will be presented in order sorted by the key.
-
-A more complicated solution is to subclass ``UserDict.UserDict``
-to create a ``SortedDict`` class that prints itself in a predictable order.
-Here's one simpleminded implementation of such a class::
+Non è possibile. I dizionari memorizzano le proprie chiavi in un ordine
+che non può essere previsto, per cui l'ordine di visualizzazione degli
+elementi di un dizionario è ugualmente non prevedibile.
+
+Questo può essere frustrante se ciò che si desidera è salvare una versione
+stampabile su un file, eseguire qualche modifica e confrontarlo con un
+altro dizionario stampato. In questo caso, si può usare il modulo 
+``pprint`` per stampare in modo gradevole il dizionario; gli elementi
+verranno presentati in ordine di chiave.
+
+Una soluzione più complessa è estendere ``UserDict.UserDict`` per creare una
+classe ``SortedDict`` che stampa se stessa in un ordine predicibile.
+Di seguito una semplice implementazione di una classe simile::
 
   import UserDict, string
 
@@ -1246,33 +1262,33 @@
     ___str__ = __repr__
 
 
-This will work for many common situations you might encounter, though
-it's far from a perfect solution. The largest flaw is that if some
-values in the dictionary are also dictionaries, their values won't be
-presented in any particular order.
+Tale classe funziona in molte situazioni comuni, anche se non è certo 
+una soluzione perfetta. Il più grave difetto è che se alcuni valori 
+del dizionario sono a loro volta dei dizionari, i loro valori non 
+verranno presentati in alcun ordine particolare.
 
-I want to do a complicated sort: can you do a Schwartzian Transform in Python?
+Si vuole effettuare un ordinamento complesso: è possibile fare una Trasformata di Schwartz in Python?
 --------------------------------------------------------------------------------------
 
-Yes, it's quite simple with list comprehensions.  
+Si, ed è piuttosto semplice con le list comprehension.
 
-The technique, attributed to Randal Schwartz of the Perl community,
-sorts the elements of a list by a metric which maps each element to
-its "sort value".  To sort a list of strings by their uppercase
-values::
+La tecnica, attribuita a Randal Schwartz della comunità Perl, ordina
+gli elementi di una lista in base a una metrica che mappa ogni elemento
+al suo "valore di ordinamento". Per ordinare una lista di stringhe
+in base al loro valore maiuscolo::
 
-  tmp1 = [ (x.upper(), x) for x in L ] # Schwartzian transform
+  tmp1 = [ (x.upper(), x) for x in L ] # Trasformata di Schwartz
   tmp1.sort()
   Usorted = [ x[1] for x in tmp1 ]
 
-To sort by the integer value of a subfield extending from positions 10-15
-in each string::
+Per ordinare in base al valore intero di un sottocampo nelle posizioni 10-15
+delle stringhe::
 
-  tmp2 = [ (int(s[10:15]), s) for s in L ] # Schwartzian transform
+  tmp2 = [ (int(s[10:15]), s) for s in L ] # Trasformata di Schwartz
   tmp2.sort()
   Isorted = [ x[1] for x in tmp2 ]
 
-Note that Isorted may also be computed by ::
+Notare che Isorted può anche essere calcolato da::
 
    def intfield(s):
        return int(s[10:15])
@@ -1283,15 +1299,15 @@
    Isorted = L[:]
    Isorted.sort(Icmp)
 
-but since this method calls ``intfield()`` many times for each element
-of L, it is slower than the Schwartzian Transform.
+ma poiché questo metodo chiama ``intfield()`` parecchie volte per ogni elemento di L,
+è più lento della trasformata di Schwartz.
 
 
-How can I sort one list by values from another list?
+Come ordinare una lista in base ai valori di un'altra lista?
 ------------------------------------------------------------
 
-Merge them into a single list of tuples, sort the resulting list, 
-and then pick out the element you want. ::
+Basta fonderle in una sola lista di tuple, ordinare la lista risultante,
+e prendere l'elemento desiderato ::
 
  >>> list1 = ["what", "I'm", "sorting", "by"]
  >>> list2 = ["something", "else", "to", "sort"]
@@ -1303,113 +1319,113 @@
  >>> result
  ['else', 'sort', 'to', 'something']
 
-An alternative for the last step is::
+Un'alternativa per l'ultimo passo è::
 
   result = []
   for p in pairs: result.append(p[1])
 
-If you find this more legible, you might prefer to use this instead of
-the final list comprehension.  However, it is almost twice as slow for
-long lists.  Why?  First, the ``append()`` operation has to reallocate
-memory, and while it uses some tricks to avoid doing that each time,
-it still has to do it occasionally, and that costs quite a bit.
-Second, the expression "result.append" requires an extra attribute
-lookup, and third, there's a speed reduction from having to make 
-all those function calls.
+Se si trova questa soluzione più leggibile, si potrebbe preferire usare
+questa piuttosto della list comprehension finale. Tuttavia, essa è quasi
+due volte più lenta per liste lunghe. Perché? In primo luogo, l'operazione
+``append()`` ha bisogno di riallocare memoria, e sebbene essa utilizzi dei 
+trucchi per evitare di farlo ogni volta, talvolta deve comunque farlo,
+e questa operazione ha un certo costo. 
+Secondariamente, l'espressione "result.append" ha bisogno di una ricerca
+di attributo in più, e infine c'è una perdita di velocità dovuta alle
+varie chiamate di funzioni.
 
 
-Objects
+Oggetti
 =============
 
-What is a class?
+Cos'è una classe?
 ------------------------
-A class is the particular object type created by executing
-a class statement.  Class objects are used as templates to create
-instance objects, which embody both the data 
-(attributes) and code (methods) specific to a datatype.
-
-A class can be based on one or more other classes, called its base
-class(es). It then inherits the attributes and methods of its base
-classes. This allows an object model to be successively refined by
-inheritance.  You might have a generic ``Mailbox`` class that provides
-basic accessor methods for a mailbox, and subclasses such as
+Una classe è il particolare tipo di oggetto creato dall'esecuzione
+di un'istruzione "class". Gli oggetti Class sono usati come 
+"template" (NdT "stampi") per creare oggetti istanza, i quali accorpano i dati
+(attributi) e il codice (metodi) di uno specifico tipo di dato.
+
+Una classe può essere basata su una o più classi, chiamate
+classi base. In tal caso, essa eredita gli attributi e i metodi dalla
+sua classe base. Questo meccanismo permette di rifinire un modello
+di oggetti tramite ereditarietà in un secondo momento. Si può avere una 
+classe generica ``Mailbox`` che fornisce i metodi di accesso basilari
+a una mailbox, e sottoclassi come
 .. [- MARK -] BEGIN PART 014 of 18
-``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox`` that handle
-various specific mailbox formats.
+``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox`` che gestiscono
+i vari formati di mailbox specifici.
 
 
-What is a method?
+Cos'è un metodo?
 -------------------------
-
-A method is a function on some object ``x`` that you normally call as
-``x.name(arguments...)``.  Methods are defined as functions inside the
-class definition::
+Un metodo è una funzione su un qualunque oggetto ``x`` che normalmente
+viene chiamata come ``x.name(arguments...)``. I metodi sono definiti
+come funzioni all'interno della definizione di classe::
 
 	class C:
 	    def meth (self, arg):
 	        return arg*2 + self.attribute    
 
-What is self?
+Cos'è self?
 ---------------------
+self è semplicemente un nome convenzionale per il primo argomento di un metodo.
+Un metodo definito come ``meth(self, a, b, c)`` dovrebbe essere chiamato come 
+``x.meth(a, b, c)`` per una qualche istanza ``x`` della classe nella quale
+avviene la definizione; il metodo chiamato crederà di essere stato chiamato
+come ``meth(x, a, b, c)``.
 
-Self is merely a conventional name for the first argument of a method.
-A method defined as ``meth(self, a, b, c)`` should be called as
-``x.meth(a, b, c)`` for some instance ``x`` of the class in which the
-definition occurs; the called method will think it is called as
-``meth(x, a, b, c)``.
-
-See also
+Consultare anche
 `Why must 'self' be used explicitly in method definitions and calls?
 <general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls>`_
 
-How do I check if an object is an instance of a given class or of a subclass of it?
+Come controllare che un oggetto sia un'istanza di una data classe o di una sua sottoclasse?
 -------------------------------------------------------------------------------------------
-
-Use the built-in function ``isinstance(obj, cls)``.  You can check if
-an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. ``isinstance(obj, (class1, class2, ...))``,
-and can also check whether an object is one of Python's built-in types, e.g.
-``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``.
-
-Note that most programs do not use ``isinstance()`` on user-defined
-classes very often.  If you are developing the classes yourself, a
-more proper object-oriented style is to define methods on the classes
-that encapsulate a particular behaviour, instead of checking the
-object's class and doing a different thing based on what class it is.
-For example, if you have a function that does something::
+Usando la funzione built-in ``isinstance(obj, cls)``. Si può controllare
+che oggetto sia istanza di un qualunque numero di classi fornendo una tupla
+invece di una singola classe, es. ``isinstance(obj, (class1, class2, ...))``,
+e si può anche controllare se un oggetto è di uno dei tipi built-in in Python,
+es. ``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``.
+
+Notare che la maggior parte dei programmi non usa molto spesso ``isinstance()`` 
+su classi definite dall'utente. Un approccio in stile più orientato 
+agli oggetti è definire sulle classi i metodi che incapsulano uno specifico 
+comportamento, piuttosto che controllare la classe dell'oggetto e fare qualcosa 
+di diverso per ogni classe (NdT cfr polimorfismo).
+Per esempio, se si ha una funzione::
 
 	def search (obj):
 	    if isinstance(obj, Mailbox):
-	        # ... code to search a mailbox
+	        # ... codice per cercare in una mailbox
 	    elif isinstance(obj, Document):
-	        # ... code to search a document
+	        # ... codice per cercare in un documento
 	    elif ...
 
-A better approach is to define a ``search()`` method on all the
-classes and just call it::
+Un approccio migliore è definire un metodo ``search()`` su tutte
+le classi, e semplicemente chiamarlo::
 
 	class Mailbox:
 	    def search(self):
-	        # ... code to search a mailbox
+	        # ... codice per cercare in una mailbox
 
         class Document:
 	    def search(self):
-	        # ... code to search a document
+	        # ... codice per cercare in un documento
 
 	obj.search()
 
 
-What is delegation?
+Cos'è la delegazione?
 ---------------------------
-
-Delegation is an object oriented technique (also called a design
-pattern).  Let's say you have an object ``x`` and want to change the
-behaviour of just one of its methods.  You can create a new class that 
-provides a new implementation of the method you're interested in changing
-and delegates all other methods to the corresponding method of ``x``.
-
-Python programmers can easily implement delegation.  For example, the
-following class implements a class that behaves like a file but
-converts all written data to uppercase::
+La delegazione è una tecnica del paradigma di sviluppo orientato 
+agli oggetti (a volte detta design pattern). Diciamo di avere
+un oggetto ``x`` e di voler modificare il comportamento di uno 
+solo dei suoi metodi. Si può creare una nuova classe che fornisca
+una nuova implementazione del metodo che interessa modificare, 
+e delegare tutti gli altri metodi ai metodi corrispondenti di ``x``.
+
+Per i programmatori Python è molto facile implementare la delegazione.
+Per esempio, la classe seguente implementa una classe che si comporta
+come un file, ma converte tutti i dati scritti in maiuscolo::
 
   class UpperOut:
         def __init__(self, outfile):
@@ -1419,18 +1435,19 @@
         def __getattr__(self, name):
               return getattr(self.__outfile, name)
 
-Here the ``UpperOut`` class redefines the ``write()`` method to
-convert the argument string to uppercase before calling the underlying
-``self.__outfile.write()`` method.  All other methods are delegated to
-the underlying ``self.__outfile`` object.  The delegation is
-accomplished via the ``__getattr__`` method; consult `the language
-reference <../../doc/ref/attribute-access.html>`_ for
-more information about controlling attribute access.
-
-Note that for more general cases delegation can get trickier. When
-attributes must be set as well as retrieved, the class must define a
-``__settattr__`` method too, and it must do so carefully.  The basic
-implementation of __setattr__ is roughly equivalent to the following::
+Qui, la classe ``UpperOut`` ridefinisce il metodo ``write()`` per convertire
+l'argomento stringa in maiuscolo prima di chiamare il metodo sottostante
+``self.__outfile.write()``. Tutti gli altri metodi sono delegati all'oggetto
+``self.__outfile`` sottostante. La delegazione è realizzata attraverso il
+metodo ``__getattr__``; consultare il `language
+reference <../../doc/ref/attribute-access.html>`_ per maggiori informazioni
+sul controllo dell'accesso agli attributi.
+
+Notare che la delegazione può diventare più complessa per casi più
+generici. Quando gli attributi devono essere impostati oltre che letti,
+la classe deve definire anche un metodo ``__settattr__``, e deve
+farlo con molta attenzione. Un'implementazione di base di __setattr__
+è approssimativamente equivalente alla seguente::
 
    class X:
         ...
@@ -1439,33 +1456,32 @@
              self.__dict__[name] = value
         ...
 
-Most __setattr__ implementations must modify
-self.__dict__ to store local state for self without
-causing an infinite recursion.
+La maggior parte delle implementazioni di __setattr__ modificano
+self.__dict__ per poter memorizzare lo stato locale di self senza 
+causare una ricorsione infinita.
 
-How do I call a method defined in a base class from a derived class that overrides it?
+Come chiamare un metodo definito in una classe base da una classe derivata che lo sovrascrive?
 ----------------------------------------------------------------------------------------------
-
-If you're using new-style classes, use the built-in ``super()`` function::
+Se si usano le classe new-style, è sufficiente usare la funzione built-in ``super()``::
 
 	class Derived(Base):
 	    def meth (self):
 	        super(Derived, self).meth()
 
-If you're using classic classes: For a class definition such as
-``class Derived(Base): ...`` you can call method ``meth()`` defined in
-``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self,
-arguments...)``.  Here, ``Base.meth`` is an unbound method, so you
-need to provide the ``self`` argument.
+Se si usano le classi classiche: per una definizione di classe come
+``class Derived(Base): ...``  si può chiamare il metodo ``meth()`` 
+definito in ``Base`` (o una delle classi base di ``Base``) come 
+``Base.meth(self, arguments...)``.  Qui, ``Base.meth`` è un metodo 
+unbound (NdT "slegato"), per cui bisogna fornirgli l'argomento ``self``.
 
-How can I organize my code to make it easier to change the base class?
+Come organizzare il codice in modo da semplificare le modifiche alla classe base?
 ------------------------------------------------------------------------------
-You could define an alias for the base class, assign the real base
-class to it before your class definition, and use the alias throughout
-your class.  Then all you have to change is the value assigned to the
-alias.  Incidentally, this trick is also handy if you want to decide
-dynamically (e.g. depending on availability of resources) which base
-class to use.  Example::
+Si può definire un alias per la classe base, assegnargli la classe reale
+prima della propria definizione di classe, e utilizzare l'alias nella
+propria classe. A questo punto, tutto ciò che bisogna modificare è il
+valore assegnato all'alias. Incidentalmente, questo trucco è utile
+anche se si vuole decidere dinamicamente (es. a seconda della disponibilità
+di risorse) quale classe base usare. Esempio::
 
         BaseAlias = <real base class>
         class Derived(BaseAlias):
@@ -1474,62 +1490,61 @@
                         ...
 
 
-How do I create static class data and static class methods?
+Come si creano dati di classe e metodi statici?
 -------------------------------------------------------------------
+Creare dati statici (nel senso di C++ o Java) è semplice; i metodi statici
+(sempre nel senso di C++ o Java) non sono invece supportati direttamente.
 
-Static data (in the sense of C++ or Java) is easy; static methods
-(again in the sense of C++ or Java) are not supported directly.
-
-For static data, simply define a class attribute.  To assign a new
-value to the attribute, you have to explicitly use the class name in
-the assignment::
+Per creare dati statici, è sufficiente semplicemente definire un attributo
+di classe. Per assegnare un nuovo valore all'attributo, bisogna usare
+il nome della classe esplicitamente nell'assegnamento::
 
     class C:
-        count = 0   # number of times C.__init__ called
+        count = 0   # numero di volte che è stato chiamato C.__init__ 
 
         def __init__(self):
             C.count = C.count + 1
 
         def getcount(self):
-            return C.count  # or return self.count
+            return C.count  # oppure return self.count
 
-``c.count`` also refers to ``C.count`` for any ``c`` such that
-``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some
-class on the base-class search path from ``c.__class__`` back to ``C``.
-
-Caution:  within a method of C, an assignment like ``self.count = 42``
-creates a new and unrelated instance vrbl named "count" in ``self``'s own dict.
-Rebinding of a class-static data name must always specify the class 
-whether inside a method or not::
+``c.count`` si riferisce anche a ``C.count`` per qualunque ``c`` tale che
+``isinstance(c, C)`` è vera, a meno che non sia sovrascritta da ``c`` 
+stesso o da una delle classi base nel percorso da ``c.__class__`` a ``C``.
+
+Attenzione: in un metodo di C, un assegnamento come ``self.count = 42``
+crea una nuova variabile di nome "count", non riferita a C, nel dizionario
+di ``self``. Per effettuare il rebind di dati statici di classe, bisogna sempre
+specificare il nome della classe, che ci si trovi all'interno di un metodo oppure no::
 
     C.count = 314
 
 
-Static methods are possible when you're using new-style classes::
+Se si usano classi di nuovo stile è possibile creare metodi statici::
 
 	class C:
 	    def static(arg1, arg2, arg3):
-		# No 'self' parameter!
+		# Nessun parametro "self"
 	        ...
 	    static = staticmethod(static)
 
-However, a far more straightforward way to get the effect of a static
-method is via a simple module-level function::
+In ogni caso, un modo molto più diretto per ottenere l'effetto di un
+metodo statico è tramite una semplice funzione a livello di modulo::
 
     def getcount():
         return C.count
 
-If your code is structured so as to define one class (or tightly
-related class hierarchy) per module, this supplies the desired
-encapsulation.
+Se il proprio codice è strutturato in modo da definire una classe
+(oppure una gerarchia di classi strettamente correlate) per modulo,
+questo metodo fornisce l'incapsulamento desiderato.
 
 
-How can I overload constructors (or methods) in Python?
----------------------------------------------------------------
-This answer actually applies to all methods, but the question
-usually comes up first in the context of constructors.
+Come si può effettuare l'overloading di costruttori (o metodi) in Python?
+-------------------------------------------------------------------------
+Questa risposta in realtà si applica a tutti i metodi, ma la domanda
+in genere viene posta principalmente riguardo ai costruttori.
 
-In C++ you'd write ::
+In C++ si scriverebbe ::
 
     class C {
         C() { cout << "No arguments\n"; }
@@ -1537,8 +1552,8 @@
     }
 .. [- MARK -] BEGIN PART 016 of 18
 
-in Python you have to write a single constructor that catches all
-cases using default arguments.  For example::
+in Python, bisogna scrivere un singolo costruttore che catturi tutti i
+casi tramite l'uso degli argomenti di default. Per esempio::
 
     class C:
         def __init__(self, i=None):
@@ -1547,138 +1562,140 @@
             else:
                 print "Argument is", i
 
-This is not entirely equivalent, but close enough in practice.
+Questo costrutto non è del tutto equivalente, ma nella pratica abbastanza
+simile.
 
-You could also try a variable-length argument list, e.g. ::
+Si potrebbe anche provare con una lista di parametri variabile, es::
 
         def __init__(self, *args):
             ....
 
-The same approach works for all method definitions.
+Lo stesso approccio funziona per la definizione di qualunque metodo.
 
 
-I try to use __spam and I get an error about _SomeClassName__spam.
+Provando ad usare __spam, si ottiene un errore riguardante _SomeClassName__spam.
 --------------------------------------------------------------------------
-Variables with double leading underscore are "mangled" to provide a
-simple but effective way to define class private variables.  Any
-identifier of the form ``__spam`` (at least two leading
-underscores, at most one trailing underscore) is textually
-replaced with ``_classname__spam``, where ``classname`` is the
-current class name with any leading underscores stripped.  
-
-This doesn't guarantee privacy: an outside user can still deliberately
-access the "_classname__spam" attribute, and private values are visible 
-in the object's ``__dict__``.  Many Python programmers never bother to use
-private variable names at all.
+Le variabili che cominciano con un doppio underscore sono sottoposte
+a "name mangling", per fornire un modo semplice ma efficace per definire
+variabili di classe private. Qualunque identificatore nella forma
+``__spam`` (almeno due underscore all'inizio, al massimo un underscore alla fine),
+è testualmente sostituito con ``_classname__spam``, dove ``classname`` è
+il nome della classe corrente con qualunque underscore iniziale rimosso.
+
+Questo non garantisce che l'attributo sia realmente privato: un utente esterno può
+sempre deliberatamente accedere all'attributo "_classname__spam", e comunque
+gli attributi privati sono visibili nel ``__dict__`` dell'oggetto. Molti 
+programmatori python non si preoccupano mai di utilizzare nomi di variabili
+privati.
 
 
-My class defines __del__ but it is not called when I delete the object.
+Una classe definisce __del__, ma esso non viene chiamato alla distruzione dell'oggetto.
 -------------------------------------------------------------------------------
-There are several possible reasons for this.
+Ci sono diversi possibili motivi per questo comportamento.
 
-The del statement does not necessarily call __del__ -- it simply
-decrements the object's reference count, and if this reaches zero
-__del__ is called.
-
-If your data structures contain circular links (e.g. a tree where each
-child has a parent reference and each parent has a list of children)
-the reference counts will never go back to zero.  Once in a while
-Python runs an algorithm to detect such cycles, but the garbage
-collector might run some time after the last reference to your data
-structure vanishes, so your __del__ method may be called at an
-inconvenient and random time. This is inconvenient if you're trying to
-reproduce a problem. Worse, the order in which object's __del__
-methods are executed is arbitrary.  You can run ``gc.collect()`` to
-force a collection, but there *are* pathological cases where objects will
-never be collected.
-
-Despite the cycle collector, it's still a good idea to define an
-explicit ``close()`` method on objects to be called whenever you're
-done with them.  The ``close()`` method can then remove attributes
-that refer to subobjecs.  Don't call ``__del__`` directly --
-``__del__`` should call ``close()`` and ``close()`` should make sure
-that it can be called more than once for the same object.
-
-Another way to avoid cyclical references is to use the "weakref"
-module, which allows you to point to objects without incrementing
-their reference count. Tree data structures, for instance, should use
-weak references for their parent and sibling references (if they need
-them!).
-
-If the object has ever been a local variable in a function that caught
-an expression in an except clause, chances are that a reference to the
-object still exists in that function's stack frame as contained in the
-stack trace.  Normally, calling ``sys.exc_clear()`` will take care of
-this by clearing the last recorded exception.  
+L'istruzione del non chiama necessariamente __del__ -- essa semplicemente
+decrementa il reference count (NdT numero di riferimenti all'oggetto)
+dell'oggetto, e quando esso raggiunge zero, solo allora viene chiamato __del__.
+
+Se una struttura dati contiene riferimenti circolari (es. un albero
+dove ogni figlio ha un riferimento al padre, e ogni padre ha una lista
+dei propri figli), i reference count degli oggetti non andranno mai a zero.
+Periodicamente Python esegue un algoritmo per individuare tale tipo
+di collegamenti, ma il garbage collector potrebbe venire eseguito diverso
+tempo dopo la distruzione dell'ultimo riferimento alla struttura dati, per
+cui il metodo __del__ potrebbe venire chiamato in un momento a caso,
+non opportuno. Questo comportamento è inopportuno se si tenta di riprodurre
+un problema. Ancora peggio, l'ordine in cui i __del__ dei vari oggetti
+vengono eseguiti è arbitrario. Si può eseguire ``gc.collect()`` per forzare
+il garbage collector, ma ci *sono* casi patologici in cui il garbage collecting
+non avverrà mai su determinati oggetti.
+
+Nonostante il cycle collector, è comunque una buona idea definire 
+esplicitamente sugli oggetti un metodo ``close()``, da chiamare quando
+si è finito di usarli. Il metodo ``close()`` può in tal caso rimuovere
+gli attributi che si riferiscono a sottooggetti. Non chiamare ``__del__``
+direttamente -- ``__del__`` dovrebbe chiamare ``close()`` e ``close()``
+dovrebbe avere la certezza di poter essere chiamato più di una volta per
+lo stesso oggetto.
+
+Un altro metodo per evitare riferimenti circolari è usare il modulo
+"weakref", che permette di creare riferimenti ad oggetti senza
+incrementare il loro reference count. Strutture dati come gli alberi, 
+per esempio, dovrebbero usare weak reference per i riferimenti
+ai genitori e ai fratelli (se ce n'è bisogno!)
+
+Se un oggetto è stato una variabile locale in una funzione che ha chiamato
+un'espressione in una clausola except, c'è qualche possibilità che esista
+ancora un riferimento all'oggetto nello stack frame della funzione, in
+quanto contenuto nello stack trace. Normalmente, chiamare ``sys.exc_clear()``
+risolve il problema eliminando l'ultima eccezione registrata.
 
-Finally, if your __del__ method raises an exception, a warning message
-is printed to sys.stderr.
+Infine, se il metodo __del__ solleva un'eccezione, un messaggio di avvertimento
+viene stampato su sys.stderr.
 
 
-How do I get a list of all instances of a given class?
+Come ottenere una lista di tutte le istanze di una data classe?
 -------------------------------------------------------------- 
+Python non tiene traccia di tutte le istanze di una classe (o
+di un tipo built-in). Si può programmare il costruttore della 
+classe per tener traccia di tutte le istanze tenendo in una 
+lista la weak reference di ogni istanza.
 
-Python does not keep track of all instances of a class (or of a
-built-in type).  You can program the class's constructor to keep track
-of all instances by keeping a list of weak references to each
-instance.
 
-
-Modules
+Moduli
 =============
-How do I create a .pyc file?
+Come si crea un file .pyc?
 -------------------------------------
+Quando un modulo è importato per la prima volta (o quando il sorgente
+è più recente del file compilato corrente), Python dovrebbe creare
+un file ``.pyc`` contenente il codice compilato nella stessa
+directory del file ``.py``.
 
-When a module is imported for the first time (or when the source is
-more recent than the current compiled file) a ``.pyc`` file containing
-the compiled code should be created in the same directory as the
-``.py`` file.
-
-One reason that a ``.pyc`` file may not be created is permissions
-problems with the directory. This can happen, for example, if you
+Un motivo per cui non viene creato il file ``.pyc`` potrebbe
+essere un problema di permessi sulla directory. Ciò può accadere,
 .. [- MARK -] BEGIN PART 017 of 18
-develop as one user but run as another, such as if you are testing
-with a web server.  Creation of a .pyc file is automatic if you're
-importing a module and Python has the ability (permissions, free
-space, etc...) to write the compiled module back to the directory.
-
-Running Python on a top level script is not considered an import and
-no ``.pyc`` will be created.  For example, if you have a top-level
-module ``abc.py`` that imports another module ``xyz.py``, when you run
-abc, ``xyz.pyc`` will be created since xyz is imported, but no
-``abc.pyc`` file will be created since ``abc.py`` isn't being
-imported.
-
-If you need to create abc.pyc -- that is, to create a .pyc file for a
-module that is not imported -- you can, using the py_compile and
-compileall modules.
+per esempio, se si sviluppa come un utente ma si esegue come un
+altro utente, come quando si esegue il testing con un web server.
+La creazione di un file .pyc è eseguita automaticamente se si importa 
+un modulo e Python è in grado (permessi, spazio libero, ecc.) di 
+scrivere il modulo compilato nella directory.
+
+Eseguire Python su uno script top-level non è considerato
+un import, per cui non sarà creato un file ``.pyc``. Per esempio,
+se si ha un modulo top-level ``abc.py`` che importa un altro modulo
+``xyz.py``, quando si esegue abc, ``xyz.pyc`` verrà creato, in quanto
+xyz è importanto, mentre ``abc.pyc`` poiché ``abc.py`` non viene
+importato.
+
+Se si ha la necessità di creare abc.pyc -- ossia, per creare un file
+.pyc per un modulo che non viene importato -- si possono utilizzare
+i moduli py_compile e compileall.
 
-The ``py_compile`` module can manually compile any module.  One way is
-to use the ``compile()`` function in that module interactively::
+Il modulo ``py_compile`` permette di compilare manualmente qualunque modulo.
+Un modo è utilizzare interattivamente la funzione ``compile()`` del modulo::
 
     >>> import py_compile
     >>> py_compile.compile('abc.py')
 
-This will write the ``.pyc`` to the same location as ``abc.py`` (or
-you can override that with the optional parameter ``cfile``).
+Questo scriverà il file ``.pyc`` nella stessa posizione di ``abc.py`` (si può
+modificare la posizione con il parametro opzionale ``cfile``).
 
-You can also automatically compile all files in a directory or
-directories using the ``compileall`` module.
-You can do it from the shell prompt by running ``compileall.py``
-and providing the path of a directory containing Python files to compile::
+E' possibile anche compilare automaticamente tutti i file in una directory
+o in varie directory utilizzando il modulo ``compileall``.
+Si può fare da un prompt o una shell eseguendo ``compileall.py``
+e fornendo il path di una directory contenente file Python da compilare::
 
        python compileall.py .
 
 
-
-How do I find the current module name?
+Come trovare il nome del modulo corrente?
 --------------------------------------------- 
-
-A module can find out its own module name by looking at the predefined
-global variable ``__name__``.  If this has the value '__main__', the
-program is running as a script.  Many modules that are usually used by
-importing them also provide a command-line interface or a self-test,
-and only execute this code after checking ``__name__``::
+Un modulo può reperire il proprio nome leggendo il valore della
+variabile globale predefinita ``__name__``. Se tale variabile ha
+il valore '__main__', il programma è in esecuzione come script.
+Molti moduli comunemente usati tramite import, prevedono anche 
+un'interfaccia da commandline, oppure dei self-test, ed eseguono 
+tale codice solo previo controllo di ``__name__``::
 
         def main():
 	    print 'Running test...'
@@ -1688,9 +1705,9 @@
 	    main()
 
 
-How can I have modules that mutually import each other?
+Come si creano moduli che si importano l'un l'altro a vicenda?
 ---------------------------------------------------------------
-Suppose you have the following modules:
+Supponiamo di avere i seguenti moduli::
 
 foo.py::
 
@@ -1702,55 +1719,55 @@
 	from foo import foo_var
 	bar_var=2
 
-The problem is that the interpreter will perform the following steps:
+Il problema è che l'interprete esegue i seguenti passi:
 
-* main imports foo
-* Empty globals for foo are created
-* foo is compiled and starts executing
-* foo imports bar
-* Empty globals for bar are created
-* bar is compiled and starts executing
-* bar imports foo (which is a no-op since there already is a module named foo)
+* main importa foo
+* Vengono create variabili globali vuote per foo
+* foo viene compilato ed eseguito
+* foo importa bar
+* Vengono create variabili globali vuote per bar
+* bar viene compilato ed eseguito
+* bar importa foo (non viene eseguita nessuna operazione dal momento che esiste già un modulo di nome foo)
 * bar.foo_var = foo.foo_var
 
-The last step fails, because Python isn't done with interpreting ``foo``
-yet and the global symbol dictionary for ``foo`` is still empty.
+L'ultimo passo fallisce, perché Python non ha ancora terminato di 
+interpretare ``foo`` e il dizionario dei simboli per ``foo`` è ancora vuoto.
 
-The same thing happens when you use ``import foo``, and then try to
-access ``foo.foo_var`` in global code.
+Lo stesso accade se si usa  ``import foo``, e successivamente si tenta
+di accedere a ``foo.foo_var`` da codice globale.
 
-There are (at least) three possible workarounds for this problem. 
+Ci sono (almeno) tre possibili scappatoie per questo problema.
 
-Guido van Rossum recommends avoiding all uses of ``from <module>
-import ...``, and placing all code inside functions.  Initializations
-of global variables and class variables should use constants or
-built-in functions only.  This means everything from an imported
-module is referenced as ``<module>.<name>``.
+Guido van Rossum raccomanda di evitare qualunque uso della forma
+``from <module> import ...``, e di posizionare tutto il codice 
+all'interno di funzioni. Per l'inizializzazione di variabili globali 
+e di classe si dovrebbero usare solo costanti o funzioni built-in.
+Questo significa che qualunque cosa di un modulo importato dovrebbe
+essere referenziata come ``<module>.<name>``.
 
-Jim Roskind suggests performing steps in the following order in each
-module:
+Jim Roskind suggerisce di eseguire i passi nel seguente ordine in ogni modulo:
 
-* exports (globals, functions, and classes that don't need imported base classes)
-* ``import`` statements
-* active code (including globals that are initialized from imported values).
+* esportazioni (variabili globali, funzioni e classe che non hanno bisogno di classi basi importate)
+* istruzioni ``import``
+* codice attivo (incluse variabili globali che vengono inizializzate da valori importati).
 
-van Rossum doesn't like this approach much because the imports
-appear in a strange place, but it does work.
+A van Rossum non piace molto questo approccio in quanto gli import
+avvengono i luoghi strani, tuttavia esso funziona.
 
 .. [- MARK -] BEGIN PART 018 of 18
-Matthias Urlichs recommends restructuring your code so that the
-recursive import is not necessary in the first place.
+Matthias Urlichs raccomanda di ristrutturare il proprio codice in
+modo da rendere gli import ricorsivi non necessari in primo luogo.
 
-These solutions are not mutually exclusive.
+Queste soluzioni non si escludono a vicenda.
 
 
-__import__('x.y.z') returns <module 'x'>; how do I get z?
+__import__('x.y.z') restituisce <module 'x'>; come ottenere z?
 -----------------------------------------------------------------------
-Try::
+Provare con::
 
    __import__('x.y.z').y.z
 
-For more realistic situations, you may have to do something like ::
+Per soluzioni più realistiche, si può avere qualcosa tipo::
 
    m = __import__(s)
    for i in s.split(".")[1:]:
@@ -1758,36 +1775,36 @@
 
 
 
-When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?
+Modificando un modulo importato, e reimportandolo, le modifiche non appaiono. Come mai accade ciò?
 --------------------------------------------------------------------------------------------------------------------------------------------
-
-For reasons of efficiency as well as consistency, Python only reads
-the module file on the first time a module is imported.  If it didn't,
-in a program consisting of many modules where each one imports the
-same basic module, the basic module would be parsed and re-parsed many
-times.  To force rereading of a changed module, do this::
+Per motivi di efficienza e consistenza, Python legge il file del modulo
+solo la prima volta che un modulo viene importato. Se così non fosse,
+in un programma formato da molti moduli in cui ognuno importa gli stessi
+moduli di base, tali moduli verrebbero parsati e riparsati parecchie volte.
+Per forzare la rilettura di un modulo modificato, si procede in questo modo::
 
         import modname
         reload(modname)
 
-Warning: this technique is not 100% fool-proof.  In particular,
-modules containing statements like ::
+Attenzione: questa tecnica non è sicura al 100%. In particolare,
+moduli contenenti istruzioni come::
 
         from modname import some_objects
 
-will continue to work with the old version of the imported objects.
-If the module contains class definitions, existing class instances
-will *not* be updated to use the new class definition.  This can
-result in the following paradoxical behaviour::
+continueranno a funzionare con la vecchia versione degli oggetti importati.
+Se un modulo contiene definizioni di classi, le istanze di classe già
+esistenti *non* saranno aggiornate per utilizzare la nuova definizione
+della classe. Questo potrebbe risultare nel comportamento paradossale
+seguente::
 
 	>>> import cls
-	>>> c = cls.C()                # Create an instance of C
+	>>> c = cls.C()                # Crea un'istanza di C
 	>>> reload(cls)
 	<module 'cls' from 'cls.pyc'>
-	>>> isinstance(c, cls.C)       # isinstance is false?!?
+	>>> isinstance(c, cls.C)       # isinstance è falso?!?
 	False
 
-The nature of the problem is made clear if you print out the class objects:
+La natura del problema viene chiarita stampando gli oggetti classe:
 
 	>>> c.__class__
 	<class cls.C at 0x7352a0>


Maggiori informazioni sulla lista Commits