``Type-checking'' with dir()

Harry Pehkonen harry.pehkonen at hotpop.com
Sat Aug 16 21:36:43 CEST 2003


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?

Thanks!
Harry.




More information about the Python-list mailing list