Flagging classes as not intended for direct initialization

Peter Otten __peter__ at web.de
Mon Feb 16 02:42:43 EST 2015


Mario Figueiredo wrote:

> Hello everyone,
> 
> [Python 3.X]
> 
> I have the following factory model for the initialization of a class
> tree (code abbreviated for simplicity).
> 
> # item.py
> class BadItemType(Exception):
>     pass
> 
> class Item:
>     def __init__(self, _data):
> 
> class Container(Item):
>     def __init__(self, _data):
>         Item.__init__(self, _data)
>         # ...
> 
> class Tool(Item):
>     def __init__(self, _data):
>         Item.__init__(self, _data)
>         # ...
> 
> def spawn(type_, id_):
>     if type_ not in Item.__subclasses__():
>         raise BadItemType()
>     # ...
>     return type_(data)
> 
> I'd like to know your opinions on an acceptable way to flag the Item
> class and its derived classes so users of this module know they should
> avoid instantiating them directly.
> 
> Other than the obvious notes on the classes docstrings, is it good
> enough I mark the constructor argument as an implementation variable as
> I did?

You can delete the class from the namespace:

class Item:
   ...

def spawn_item(id, class_=Item):
   ...
   return class_(data)

del Item





More information about the Python-list mailing list