``Type-checking'' with dir()

Raymond Hettinger vze4rx4y at verizon.net
Sat Aug 16 23:33:54 CEST 2003

"Harry Pehkonen" <harry.pehkonen at hotpop.com> wrote in message
news:70df36e9.0308161136.3c414a80 at posting.google.com...
> In order to leave my classes open to receiving objects that are
> string-like, list-like, dictionary-like, etc, and not necessarily
> _exactly_ the built-in string, list, dictionary, etc types, I have the
> desire to just check if the necessary methods exist.  Instead of:
>     if type(a) == type(""):
>         ...
> . . . I like:
>     wanted_methods = ["__getslice__", "__len__"]
>     if len([ m
>               for m in dir(a)
>               if m in wanted_methods ]) == len(wanted_methods):
>         ...
> In the above example, I might want to get a slice of variable a if
> it's length is appropriate.  The above code is a simplified in-line
> version of, say, has_methods().  Any thoughts?

The code becomes especially clean if you use the sets module:

     if not Set(["__getslice__", "__len__"]) < Set(dir(a)):
              raise InterfaceError(a)

Raymond Hettinger

More information about the Python-list mailing list