Nesting Custom Errors in Classes

DL Neil PythonList at DancesWithMice.info
Mon Jul 22 22:54:04 EDT 2019


Do you use nested classes?

[following-on from the earlier, "Namespaces: memory vs 'pollution'" 
discussion thread, wherein a certain 'someone' remembered to from ... 
import ... as ... an 'action' class but forgot to also import the 
related custom error class! The original quest was for a wild-card 
import device. This discussion may obviate continuing the quest and/or 
needing to remember...]


Python manages nested classes.

I've NEVER seen such 'in the wild'.
(but perhaps I lead a sheltered life?)


What are proposed as use-cases for such a technique?
- other languages may not offer decent "inheritance", and this is an 
alternative method/hack
- the class is a 'class factory', generating/returning an object
? any others


Why not use it as an "encapsulation" device?
(please be gentle - reminder: I am too old to have been an OO-native!)


***** stub definitions

 >>> class PythonEnvironment():
...     class PythonVersionError( EnvironmentError ):
...             pass
...     def iscompatible( self ):
		''' Ensure that the Python in-use will support
		all of the facilities employed by the application.
		'''
...             # stub to simulate failure
...             raise self.PythonVersionError
...

(code would require an import or from ... import ...)
 >>> pe = PythonEnvironment()


***** its basic application becomes:-

 >>> pe.iscompatible()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 6, in compatibility
__main__.PythonVersionError


***** somewhat more realistic use:-

 >>> try:
...     pe.iscompatible()
... except PythonEnvironment.PythonVersionError:
...     print( "Trapped! -> informative errmsg" )
...
Trapped! -> informative errmsg


With this construct, one only has to import the 'outer' class, rather 
than both the class AND its ancillary error class!


Why haven't I seen it before? Can you see anything 'wrong' with this 
picture?
-- 
Regards,
=dn



More information about the Python-list mailing list