selective (inheriting?) dir()?

Chris Angelico rosuav at gmail.com
Mon Apr 21 10:38:16 EDT 2014


On Tue, Apr 22, 2014 at 12:06 AM, Skip Montanaro <skip at pobox.com> wrote:
> Without examining the source, is
> it possible to define some kind of "selective" dir, with a API like
>
>     def selective_dir(inst, class_): pass
>
> which will list only those attributes of inst which were first defined
> in (some method defined by) class_? The output of calls with different
> class_ args would yield different lists:
>
>     selective_dir(inst_b, B) -> ['y']
>
>     selective_dir(inst_b, A) -> ['x']
>
> I'm thinking some sort of gymnastics with inspect might do the trick,
> but after a quick skim of that module's functions nothing leapt out at
> me.

Hmm. Interesting.

Fundamentally, attributes in Python don't give you anything about
which class they were defined in... by default. However, it ought to
be possible to play around with the metaclass; it could detect that
you're creating a new attribute and record that somewhere.

But if you know that all the attributes you care about are set in
__init__, you could do some analysis on that, as you were looking at.
Might turn out to be a lot of work to dig through the compiled code,
though.

ChrisA



More information about the Python-list mailing list