``Type-checking'' with dir()

H

Harry Pehkonen

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.
 
R

Raymond Hettinger

Harry Pehkonen said:
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
 
A

Alex Martelli

Raymond Hettinger wrote:
...
The code becomes especially clean if you use the sets module:

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

I think you want a <= here -- otherwise, an InterfaceError would
be raised in the (unlikely, sure;-) case in which dir(a) has
ONLY the __len__ and __getslice__ entries.

(BTW, of course: __getslice__ is obsolete, and properly substituted
by __getitem__ taking a slice object as an 'index' in today's
well-implemented sequences -- so, this is not a good example
[not Raymond's fault, of course, as it was what the OP used]).


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top