Check if object is file-like in Python

后端 未结 8 830
抹茶落季
抹茶落季 2020-12-01 00:02

File-like objects are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of

8条回答
  •  爱一瞬间的悲伤
    2020-12-01 00:28

    It's often useful to raise an error by checking a condition, when that error normally wouldn't be raised until much later on. This is especially true for the boundary between 'user-land' and 'api' code.

    You wouldn't place a metal detector at a police station on the exit door, you would place it at the entrance! If not checking a condition means an error might occur that could have been caught 100 lines earlier, or in a super-class instead of being raised in the subclass then I say there is nothing wrong with checking.

    Checking for proper types also makes sense when you are accepting more than one type. It's better to raise an exception that says "I require a subclass of basestring, OR file" than just raising an exception because some variable doesn't have a 'seek' method...

    This doesn't mean you go crazy and do this everywhere, for the most part I agree with the concept of exceptions raising themselves, but if you can make your API drastically clear, or avoid unnecessary code execution because a simple condition has not been met do so!

提交回复
热议问题