Flagging classes as not intended for direct initialization

Mario Figueiredo marfig at gmail.com
Mon Feb 16 05:55:45 EST 2015


In article <54e14cfe$0$12997$c3e8da3$5496439d at news.astraweb.com>, 
steve+comp.lang.python at pearwood.info says...
> 
> If this is a type error, why aren't you using TypeError? Or at least
> inheriting from TypeError?
> 

Yeah. It's not that I'm gaining much from that abstraction. It's not 
even an abstraction, it's just masking since there really won't be any 
specific logic to that exception. You are right. Removed it.

> 
> Unless you have good reason not to, you should use super rather than
> directly call the superclass.
> 
> https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

It's not been an easy ride trying to decide whether or not to use super. 
I started learning python from a Mark Lutz book that advised me against 
it. And on the web I get all sorts of information pro and against. Seems 
like everyone has an opinion and theirs the correct one.

I have not delved deep into that construct to decide for myself. But 
thanks for the link. It actually addresses more than most and builds a 
pretty good case for it.

> 
> Are users supposed to subclass Item themselves? If so, you should make Item
> an ABC (Abstract Base Class):
> 
> class ItemABC:
>     def __init__(self, data):
>         if type(self) is ItemABC:
>             raise TypeError("You must subclass ItemABC")
> 

Ooh! Was forgetting about that. Thanks.

> 
> But if users aren't supposed to use the classes *at all*, but only use the
> spawn factory function, you don't have a lot of good choices in pure Python
> code. Python isn't designed to be that restrictive.
> 
> The *simplest thing which will work* is simply not worry about it. You
> should consider the factory function to be merely for convenience. It might
> be *really* convenient, but if the user wants to ignore the factory and
> reinvent the wheel, why should you care? Just document the fact that people
> are expected to use the factory, but don't expressly prohibit the use of
> the classes directly.

Yeah. I think this is best. It is one of the things I like about Python. 
This mentality not only simplifies code but also gives room for 
tinkerers to do their thing without unnecessary barriers.

I was more concerned with visibility and letting users know how to 
properly use that class tree. And docstrings are good enough. The data 
argument used in the classes initialization is a dict containing the 
necessary initialization data. So without reading the class source and 
documentation, a user has no way of knowing how to initialize those 
classes directly, anyways.

Thanks.



More information about the Python-list mailing list