开发者

How to check if a variable's type is primitive?

开发者_如何学JAVA

I don't know how to check if a variable is primitive. In Java it's like this:

if var.isPrimitive():


Since there are no primitive types in Python, you yourself must define what you consider primitive:

primitive = (int, str, bool, ...)

def is_primitive(thing):
    return isinstance(thing, primitive)

But then, do you consider this primitive, too:

class MyStr(str):
    ...

?

If not, you could do this:

def is_primitive(thing):
    return type(thing) in primitive


As every one says, there is no primitive types in python. But I believe, this is what you want.

def isPrimitive(obj):
    return not hasattr(obj, '__dict__')

isPrimitive(1) => True
isPrimitive("sample") => True
isPrimitive(213.1311) => True
isPrimitive({}) => True
isPrimitive([]) => True
isPrimitive(()) => True


class P:
    pass

isPrimitive(P) => False
isPrimitive(P()) => False

def func():
    pass

isPrimitive(func) => False


In Python, everything is an object; even ints and bools. So if by 'primitive' you mean "not an object" (as I think the word is used in Java), then there are no such types in Python.

If you want to know if a given value (remember, in Python variables do not have type, only values do) is an int, float, bool or whatever type you think of as 'primitive', then you can do:

 if type(myval) in (int, float, bool, str ...):
      # Sneaky stuff

(Need I mention that types are also objects, with a type of their own?)

If you also need to account for types that subclass the built-in types, check out the built-in isinstance() function.

Python gurus try to write code that makes minimal assumptions about what types will be sent in. Allowing this is one of the strengths of the language: it often allows code to work in unexpected ways. So you may want to avoid writing code that makes an arbitrary distinction between types.


It's not easy to say definitely what to consider 'primitive' in Python. But you can make a list and check all you want:

is_primitive = isinstance(myvar, (int, float, bool)) # extend the list to taste


For Python 2.7, you may want to take a look at types module, that lists all python built-in types.

https://docs.python.org/2.7/library/types.html

It seems that Python 3 does not provide the same 'base' type values as 2.7 did.


isinstance(obj, (str, numbers.Number) should be close enough:

How to check if a variable's type is primitive?


If it helps,

In [1]: type(1)
Out[1]: <type 'int'>

In [2]: type('a')
Out[2]: <type 'str'>

In [3]: (type(5.4)
Out[3]: <type 'float'>

In [5]: type(object)
Out[5]: <type 'type'>

In [8]: type(int)
Out[8]: <type 'type'>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜