Re: duck-type-checking?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Terry Reedy

    Re: duck-type-checking?

    Cristina Yenyxe González García wrote:
    2008/11/12 Joe Strout <joe@strout.net >:
    >So I need functions to assert that a given identifier quacks like a string,
    >or a number, or a sequence, or a mutable sequence, or a certain class, or so
    >on. (On the class check: I know about isinstance, but that's contrary to
    >duck-typing -- what I would want that check to do instead is verify that
    >whatever object I have, it has the same public (non-underscore) methods as
    >the class I'm claiming.)
    >>
    >Are there any standard methods or idioms for doing that?
    >
    You can use hasattr(object, name), with 'name' as the name of the
    public method to check. It returns True if the object responds to that
    method, False otherwise.
    Too hard. For methods, which are what define duck species, and any
    attribute guaranteed to not be null, "assert ob.name" is equivalent to
    "assert hasattr(ob, 'name')".

    tjr

  • George Sakkis

    #2
    Re: duck-type-checking?

    On Nov 12, 1:35 pm, Terry Reedy <tjre...@udel.e duwrote:
    Cristina Yenyxe González García wrote:
    >
    2008/11/12 Joe Strout <j...@strout.ne t>:
    So I need functions to assert that a given identifier quacks like a string,
    or a number, or a sequence, or a mutable sequence, or a certain class,or so
    on. (On the class check: I know about isinstance, but that's contraryto
    duck-typing -- what I would want that check to do instead is verify that
    whatever object I have, it has the same public (non-underscore) methods as
    the class I'm claiming.)
    >
    Are there any standard methods or idioms for doing that?
    >
    You can use hasattr(object, name), with 'name' as the name of the
    public method to check. It returns True if the object responds to that
    method, False otherwise.
    >
    Too hard. For methods, which are what define duck species, and any
    attribute guaranteed to not be null, "assert ob.name" is equivalent to
    "assert hasattr(ob, 'name')".
    As you just showed they're not; one raises AttributeError and the
    other AssertionError. Not that it matters much but these are typically
    reported differently by testing frameworks.

    George

    Comment

    Working...