How to handle “duck typing” in Python?

前端 未结 5 826
生来不讨喜
生来不讨喜 2020-12-08 07:46

I usually want to keep my code as generic as possible. I\'m currently writing a simple library and being able to use different types with my library feels extra important th

5条回答
  •  长情又很酷
    2020-12-08 08:19

    If you just want the unimplemented methods to do nothing, you can try something like this, rather than the multi-line try/except construction:

    getattr(obj, "sleep", lambda: None)()
    

    However, this isn't necessarily obvious as a function call, so maybe:

    hasattr(obj, "sleep") and obj.sleep()
    

    or if you want to be a little more sure before calling something that it can in fact be called:

    hasattr(obj, "sleep") and callable(obj.sleep) and obj.sleep()
    

    This "look-before-you-leap" pattern is generally not the preferred way to do it in Python, but it is perfectly readable and fits on a single line.

    Another option of course is to abstract the try/except into a separate function.

提交回复
热议问题