Skip to content Skip to sidebar Skip to footer

The Dir Function In Python

help(dir): dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprisi

Solution 1:

  1. Methods are attributes in Python.

  2. Check the various attributes on them. Methods have im_* attributes.

Solution 2:

You kind of get a feel for telling the difference, but methods are attributes, so the only way to be really sure is to check.

Here's a function that will break it down for you:

defdirf(obj=None):
    """Get the output of dir() as a tuple of lists of callables and non-callables."""
    d = ([],[])
    for name indir(obj):
        ifcallable(getattr(obj, name, locals().get(name))):
            d[0].append(name)
        else:
            d[1].append(name)
    return d

inspect.getmembers has a nice shortcut for getting callable members:

from inspect import getmembers
getmembers(obj, callable)

but beware of its own predicates! inspect.ismethod will only be True for methods implemented in Python. Many core objects' methods ([].sort, for example) do not meet that criteria.

Solution 3:

The help file is correct. In Python, methods are attached to classes (and instances of those classes) in exactly the same way as any other attribute. In order to distinguish a simple attribute from a callable one, you'll have to dereference it:

>>> type(AddrBookEntry('tom','123').phone)
<type'str'>
>>> type(AddrBookEntry('tom','123').updatePhone)
<type'instancemethod'>

Solution 4:

If you want to know the attributes of an object use the __dict__ attribute. E.g.:

>>> entry = AddrBookEntry('tom','123')
>>> entry.__dict__
{'name': 'tom', 'phone': '123'}

dir() is intended for debugging. Using it in production code is probably a bad idea. Exactly what it returns isn't very well defined.

Post a Comment for "The Dir Function In Python"