Using a subclass for __dict__

Demian Brecht demianbrecht at gmail.com
Thu Feb 13 21:07:09 CET 2014


On Thu, Feb 13, 2014 at 11:10 AM, Peter Otten <__peter__ at web.de> wrote:
> I don't really understand what you are trying to do in the gist, perhaps you want
>
> <http://docs.python.org/dev/reference/datamodel.html#customizing-instance-and-subclass-checks>

Even though you've already answered my question, here's what I'm trying to do:

High level goal (again, purely proof of concept): Piggy back on
CPython's abc implementation in order to ensure that class A
implements the interface implemented by unrelated class B.

Using abc's as intended, when @abc.abstractmethod is used, it tags the
method with __isabstractmethod__. When ABCMeta.__new__ executes, it
compiles a frozenset (__abstractmethods__) of all methods still tagged
as __isabstractmethod__ (in other words, those that haven't been
implemented in a child class). During object creation in the
interpreter layer, it checks to see if there are any
__abstractmethods__. If there is, then it fails at that point, citing
those methods as not being implemented.

All I did (and it definitely needs some good cleaning) is inject
abstractmethods in class A where implementations matching class B's
interface were not present. The specific problem that I ran into was
when methods are bound to a class definition after initial class
construction. Having said that, this seems to be more of an issue with
2.7's abc implemention:

import abc

class A(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def fn(self): pass


class B(A):
    pass

try:
    B()
except TypeError:
    pass

B.fn = lambda: 'foo'

B()

The above code works fine in 3.3, but fails in 2.7. Cool, glad that's explained.

>
> ?
>
> Anyway, intercepting __setattr__() in the class becomes easy once you remember that a class is just
> an instance of its metaclass

*Throws keyboard across the office*

FFS. I could have SWORN I tried that (because I /know/ that a class is
an instance of its metaclass :/). An instance of looking at something
far too long without a fresh set of eyes.

Thanks!

-- 
Demian Brecht
http://demianbrecht.github.com



More information about the Python-list mailing list