Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dir() without built-in methods

Tags:

python

Is there some way to get all of the attributes of an object without the built ins? I'm hoping to achieve this without the types package or without manually checking for double underscores if possible.

I've tried dir, but it gives me all the built-in stuff. Ideally i'd like something like

class A():
    foo = 'bar'
>>>> dir(a)
['foo']

instead of

>>>> dir(a)
['__doc__', '__module__', 'foo']
like image 887
Mike Avatar asked Feb 04 '14 04:02

Mike


People also ask

What does dir () do in python?

Python dir() Function The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object.

What is the syntax of dir () function?

Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be called and must return the list of attributes. It takes a single object type argument.

What is the use of help () and dir () functions in python?

Help() and dir(), are the two functions that are reachable from the python interpreter. Both functions are utilized for observing the combine dump of build-in-function. These created functions in python are truly helpful for the efficient observation of the built-in system.

What is __ dir __ in python?

Python dir() The function dir python is responsible for returning the valid list of the attributes for the objects in the current local scope. For example: If an object of a method called is named as __dir__(), the function must return a list of attributes that are associated with that function.


1 Answers

Do you just want to filter out the "special" methods, or actually know which methods are implemented in the instance itself, not inherited from a base (or both, as these are different questions, really)?

You can filter out the special methods with something reasonably simple like:

def vdir(obj):
    return [x for x in dir(obj) if not x.startswith('__')]

>>> vdir(a)
['foo']
like image 147
Nick Bastin Avatar answered Oct 19 '22 18:10

Nick Bastin