开发者

Type checking in Python

How can I check the type of function's开发者_如何转开发 parameters? For example,

def hello(x):
   # check if x is tuple
   # check if x is dictionary.
   ...

EDIT

isinstance(x, type(()))
isinstance(x, type({}))


You don't.

You should never be unsure of the type of a thing in python; it's basically impossible to check accurately. While it is possible to do some naïve surface-level checking, the problem is that python is very flexible. Your function shouldn't care if it's passed a dict or something that behaves exactly like a dict, and the best way to deal with this is to not check at all.

The real question is "why don't I know what the type of something is?"


If you really want to check that, you can use isinstance()

See also this comparison of type checking methods and why you should not check!


Python's best practice is to use duck typing: if it walks like duck and quacks like a duck, treat it like a duck. So, what you care is not whether something is a dict or a list: you care whether or not you can treat is as such (in the duck analogy, you don't care if it's a human, as long as it can walk like a duck and quack like a duck).

For instance, if you want to extract an element:

def get_element(obj, index):
 return obj[index]

works as long as the object you passed to it understands what does [index] means.

Now, you can actually use isinstance to check if an object is an instance of a class, but this is normally used for introspection purposes. I have used it, on occasion, instead of duck typing, only to regret later and go back to Python's best practice.

So, I recommend that you look at what you are trying to achieve and see if you could use duck typing instead.

Cheers.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜