How to tell which subclass was used to instantiate object

Heather Coppersmith me at privacy.net
Sat May 1 09:40:18 EDT 2004


On 1 May 2004 05:47:20 -0700,
frank at chagford.com (Frank Millman) wrote:

[ details of a multi-level object hierarchy, and worries of __init__
methods bypassing it ]

> By inheriting from the incorrect class, the special methods to
> handle a 'Master' type table have been bypassed. My question is,
> how can Table check that objects have inherited from the correct
> subclasses?

Python usually takes the "we're all adults here" point of view,
and leaves that question to unit tests and/or code reviews.  No
amount of B&D is sufficient to protect from a malicious coder
anyway.

> Here is my inelegant solution. Assume that table_type contains
> the string 'Master'.

> class Master(Table):
>     def __init__(self,table_name,table_type):
>         self.my_type = 'Master'
>         Table.__init__(self,table_name,table_type)

> class Table:
>     def __init__(self,table_name,table_type):
>         if hasattr(self,'my_type'):
>             ok = (self.my_type == table_type)
>         else:
>             ok = False
>         if not ok:
>             raise RuntimeError('%s must be of type %s' %
>                (table_name,table_type))

> Is there a more direct way for a top-level class to determine
> which subclasses were used to instantiate it?

You could add another (optional) parameter to Table.__init__, but
that's really the same solution with new syntactic sugar.

You could unwind the stack frame and look at who's calling
Table.__init__, but that's rather un-Pythonic, too.

IMO, the most Pythonic solution is to provide factory functions
that do the Right Thing instead of instantiating your classes
directly from your application code.

HTH,
Heather

-- 
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli



More information about the Python-list mailing list