Nesting Custom Errors in Classes

Cameron Simpson cs at cskk.id.au
Tue Jul 23 07:55:41 EDT 2019


On 23Jul2019 14:54, DL Neil <PythonList at DancesWithMice.info> wrote:
>Do you use nested classes?
>Python manages nested classes.
>
>I've NEVER seen such 'in the wild'.
>(but perhaps I lead a sheltered life?)

So sheltered :-)

In my experience it's uncommon. I've done it a few times.

"Nested" classes aren't anything very special; they're no more than yet 
another name defined inside a class, like a method, or a "constant".  
Look:

  class Foo:

    DEFAULT_FOO_MAX = 10

    def __init__(...):
      ...

    class SpecialThing:
      ...

They're all just various names in the class space.

I would do it if SpecialThing wasn't meaningful outside of the class 
i.e. didn't really have a standalone use.

Aside from not polluting the top level namespace with names that aren't 
useful on their own (which is kind of irrelevant since people tend to 
"from foo import name", so the _number_ of available names isn't very 
important)...

One potential benefit to to associating the inner class with the outer 
class is the inheritance chain. Look:

  class Foo:

    class ClassyThing:
      ...

    def frob(self, it):
      for i in it:
        x = self.ClassyThing(i)
        x.do_something_classy(...)

  class Bah(Foo):

    class ClassyThing:
      ...

  f = Foo()
  f.frob([1,2,3])

  b = Bah()
  b.frob([1,2,3])

Foo and Bah have a common method "frob", but f.frob will generate and 
use Foo.ClassyThing objects while b.frob will generate Bah.ClassyThing 
objects. Same code.

Personally, I haven't done the above. But I have made subclasses where 
the subclass overrides a constant, like DEFAULT_FOO_MAX earlier. Then 
accessing self.DEFAULT_FOO_MAX finds the appropriate constant.

And on thinking about it, while I haven't explicitly nested classes, I 
have passed in a class to the init method, for example an indexclass.  
I've a package which support several backend hash indices, such as gdbm, 
and I pass in the target index class. So a class as a parameterisable or 
inheritable thing isn't nonsensical.

I have use nested classes when the nested class is strongly associated 
with the enclosing class, like your classname.exceptionname example. I'd 
put it inside the outer class entirely to express that association.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list