list of 'magic methods' or builtin class methods... want to exclude those from dir output
Terry Reedy
tjreedy at udel.edu
Wed Jul 22 15:24:19 EDT 2009
DG 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!
3.1
>>> list(filter(lambda s: s[0:2]!='__', dir(object)))
[]
Now substitute your object for lambda. This assumes of course that you
are doing no name-mangling __xxx names.
tjr
More information about the Python-list
mailing list