开发者

Is it common/good practice to test for type values in Python?

开发者 https://www.devze.com 2023-01-09 05:57 出处:网络
Is it common in Python to keep testing for type values when working in a OOP fashion? class Foo(): def __init__(self,barObject):

Is it common in Python to keep testing for type values when working in a OOP fashion?

class Foo():
    def __init__(self,barObject):
        self.bar = setBarObject(barObject)

    def setBarObject(barObject);
        if (isInstance(barObject,Bar):
            self.bar = barObject
        else:
            # throw exception, log, etc.

class Bar():
    pass
开发者_开发百科

Or I can use a more loose approach, like:

class Foo():
    def __init__(self,barObject):
        self.bar = barObject

class Bar():
    pass


Nope, in fact it's overwhelmingly common not to test for type values, as in your second approach. The idea is that a client of your code (i.e. some other programmer who uses your class) should be able to pass any kind of object that has all the appropriate methods or properties. If it doesn't happen to be an instance of some particular class, that's fine; your code never needs to know the difference. This is called duck typing, because of the adage "If it quacks like a duck and flies like a duck, it might as well be a duck" (well, that's not the actual adage but I got the gist of it I think)

One place you'll see this a lot is in the standard library, with any functions that handle file input or output. Instead of requiring an actual file object, they'll take anything that implements the read() or readline() method (depending on the function), or write() for writing. In fact you'll often see this in the documentation, e.g. with tokenize.generate_tokens, which I just happened to be looking at earlier today:

The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects (see section File Objects). Each call to the function should return one line of input as a string.

This allows you to use a StringIO object (like an in-memory file), or something wackier like a dialog box, in place of a real file.

In your own code, just access whatever properties of an object you need, and if it's the wrong kind of object, one of the properties you need won't be there and it'll throw an exception.


I think that it's good practice to check input for type. It's reasonable to assume that if you asked a user to give one data type they might give you another, so you should code to defend against this.

However, it seems like a waste of time (both writing and running the program) to check the type of input that the program generates independent of input. As in a strongly-typed language, checking type isn't important to defend against programmer error.

So basically, check input but nothing else so that code can run smoothly and users don't have to wonder why they got an exception rather than a result.


If your alternative to the type check is an else containing exception handling, then you should really consider duck typing one tier up, supporting as many objects with the methods you require from the input, and working inside a try. You can then except (and except as specifically as possible) that. The final result wouldn't be unlike what you have there, but a lot more versatile and Pythonic.

Everything else that needed to be said about the actual question, whether it's common/good practice or not, I think has been answered excellently by David's.


I agree with some of the above answers, in that I generally never check for type from one function to another.

However, as someone else mentioned, anything accepted from a user should be checked, and for things like this I use regular expressions. The nice thing about using regular expressions to validate user input is that not only can you verify that the data is in the correct format, but you can parse the input into a more convenient form, like a string into a dictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消