list of 'magic methods' or builtin class methods... want to exclude those from dir output

DG dangets at gmail.com
Wed Jul 22 14:28:58 EDT 2009


On Jul 22, 12:24 pm, DG <dang... at gmail.com> wrote:
> On Jul 22, 12:15 pm, DG <dang... at gmail.com> wrote:
>
>
>
> > There is probably a better way to do this (please enlighten me, if you
> > know), but what I want to do is get a list of a class' attributes
> > minus whatever the 'builtin' methods are.  I would also like to do
> > this for instances of classes as well.  I don't want to use __dict__
> > because I want to get all of the attributes that have been added
> > throughout the inheritance tree, just not the builtin ones.
>
> > I was wondering if there is a function to return a list of these, so I
> > could perform a 'dir' on the object (class or instance) and filter out
> > the builtin attributes.  I know I could create my own list something
> > like
> > ['__class__', '__delattr__', ..., '__weakref__'] and use that.  I
> > would see this being fragile to Python version differences as new ones
> > are added or taken away.
>
> > A more flexible way is to have the list be filled out dynamically by
> > creating a 'junk' class that inherits only from object and storing
> > it's dir() output into the filter list.  This is probably what I'll do
> > unless someone knows of a builtin function that will give me a
> > (version-safe) list.
>
> > Thanks!
>
> Haha, replying to my own post.  Here is the implementation of my idea
> of dynamically creating the filter lists from a 'junk' object.  As of
> now it appears that the dir output of a class is the same as the dir
> output of an instance, but if that ever changes, this should future
> proof it.  This is only a 4-liner, so it is probably good enough for
> what I want to do, but I would rather use a builtin/standard way if
> there is one.
>
> class A(object):
>     pass
> class_filter_methods = dir(A)
> instance_filter_methods = dir(A())

Wow, I'm a quick one. Sharp as a marble.  2-liner:

class_filter_methods = dir(object)
instance_filter_methods = dir(object())



More information about the Python-list mailing list