nntp2http.com
Posting
Suche
Optionen
Hilfe & Kontakt

eccezione e getattr (e property)

Von: Enrico (4564@755189.45) [Profil]
Datum: 01.07.2008 12:26
Message-ID: <486a067e$0$18146$4fafbaef@reader3.news.tin.it>
Newsgroup: it.comp.lang.python
Ciao,
ho un piccolo problema nel gestire una eccezione utilizzando __getattr__.
Posto un piccolo estratto di codice:

>>> class A(object):
def __getattr__(self, name):
raise AttributeError('A has no %s' % name)

>>> class B(object):
def __getattr__(self, name):
raise AttributeError('B has no %s' % name)

>>> class C(A):
def __init__(self):
self.b = B()
def get_b(self):
return self.b.value
prop_b = property(get_b)

>>> c=C()
>>> c.prop_b

Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
c.prop_b
File "<pyshell#27>", line 3, in __getattr__
raise AttributeError('A has no %s' % name)
AttributeError: A has no prop_b

Da quel che mi pare di capire se la funzione get_b associata a prop_b nella
classe C genera una eccezione di tipo AttributeError, viene invocata la
__getattr__ del padre mascherando completamente l'eccezione precedente. Ho
provato a vedere dentro la __getattr__ di A ma non ci sono eccezioni attive
all'inizio della funzione.
Se sostituisco l'eccezione in B con qualcos'altro, ad esempio:

>>> class B(object):
def __getattr__(self, name):
raise ValueError('B has no %s' % name)

ottengo invece

Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
c.prop_b
File "<pyshell#37>", line 5, in get_b
return self.b.value
File "<pyshell#35>", line 3, in __getattr__
raise ValueError('B has no %s' % name)
ValueError: B has no value

Il cambiare tipo di eccezione in B non mi sembra corretto e soprattutto
nella documentazione per __getattr__ è chiaramente detto che: This method
should return the (computed) attribute value or raise an AttributeError
exception. Allora la mia domanda è: c'è un altro modo per sapere che
l'eccezione è stata generata in B e non in A?
Anche l'opzione di togliere la property non mi piace molto anche se questo
risolverebbe il problema scrivendo:
>>> c.get_b()

Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
c.get_b()
File "<pyshell#45>", line 5, in get_b
return self.b.value
File "<pyshell#49>", line 3, in __getattr__
raise AttributeError('B has no %s' % name)
AttributeError: B has no value

Se qualcuno ha qualche idea è il benvenuto
Grazie, Enrico



[ Auf dieses Posting antworten ]

Antworten