[Python] setdefault nei dict

Marco Mariani marco.mariani a prometeia.it
Gio 15 Lug 2010 12:43:29 CEST


On Thu, 2010-07-15 at 12:30 +0200, Daniele Varrazzo wrote:


> La stai eseguendo tu "a mano" scrivendo "fun1()", con le parentesi.
> 
> Prova a.setdefault(1, fun1)


In questo modo avrai alcuni (se non tutti) i valori del dizionario che
sono oggetti callable e vanno valutati al momento dell'utilizzo:

a[1]()

Se i tipi degli altri valori sono oggetti "semplici" e non callable,
puoi anche estendere la classe dict e modificare __getitem__ in modo che
valuti i valori che vuoi siano lazy:


> >>> class mydict(dict):
> ...     def __getitem__(self, k):
> ...         v = dict.__getitem__(self, k)
> ...         if callable(v):
> ...             return v()
> ...         else:
> ...             return v
> ... 
> >>> 
> >>> 
> >>> d1 = dict()
> >>> d1[1] = lambda: 4
> >>> d1[2] = 5
> >>> 
> >>> d2 = mydict()
> >>> d2[1] = lambda: 4
> >>> d2[2] = 5
> >>> 
> >>> 
> >>> print d1[1], d1[2]
> <function <lambda> at 0xb76bc764> 5
> >>> print d2[1], d2[2]
> 4 5







Il contenuto e gli allegati di questo messaggio sono strettamente confidenziali, e ne sono vietati la diffusione, la riproduzione e l'uso non autorizzato. Il suo contenuto non costituisce impegno da parte della Societą salvo accordo scritto tra quest'ultima ed il destinatario. Qualora il presente messaggio Le fosse pervenuto per errore, La preghiamo di comunicare immediatamente al mittente l'errata ricezione e di distruggere quanto ricevuto (compresi i file allegati) senza farne copia.
Qualsivoglia utilizzo non autorizzato del contenuto di questo messaggio costituisce violazione dell'obbligo di non rivelare il contenuto della corrispondenza tra altri soggetti, salvo pił grave illecito, ed espone il responsabile alle relative conseguenze.

This e-mail (and any attachment(s)) is strictly confidential and for use only by intended recipient(s). Any use, distribution, reproduction or disclosure by any other person is strictly prohibited. The content of this e-mail does not constitute a commitment by the Company except where provided for in a written agreement between this e-mail addressee and the Company. If you are not an intended recipient(s), please notify the sender promptly and destroy this message and its attachments without reading or saving it in any manner.
Any non authorized use of the content of this message constitutes a violation of the obligation to abstain from learning of the correspondence among other subjects, except for more serious offence, and exposes the person responsible to the relevant consequences.



Maggiori informazioni sulla lista Python