检查变量的类型是否是原始的

时间:2023-01-23 16:27:33

maybe this question is a bit stupid but I don't know how to check if a variable is primitive. In java it's like this:

也许这个问题有点愚蠢,但我不知道如何检查变量是否是原始的。在java中它是这样的:

if var.isPrimitive():

Thank you.

7 个解决方案

#1


32  

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

由于Python中没有原始类型,您自己必须定义您认为原始的:

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

#2


22  

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.

在Python中,一切都是对象;即使是内联和布尔。因此,如果用“原始”表示“不是对象”(因为我认为这个词在Java中使用),那么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:

如果你想知道一个给定的值(记住,在Python变量中没有类型,只有值可以)是int,float,bool或你认为是“原始”的任何类型,那么你可以这样做:

 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.

如果您还需要考虑子类化内置类型的类型,请查看内置的isinstance()函数。

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.

Python专家尝试编写代码,对发送的类型做出最小的假设。允许这是该语言的优势之一:它通常允许代码以意想不到的方式工作。因此,您可能希望避免编写在类型之间进行任意区分的代码。

#3


19  

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

正如每个人所说,python中没有原始类型。但我相信,这就是你想要的。

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

#4


6  

You may want to take a look at types module, that lists all python built-in types.

您可能需要查看types模块,它列出了所有python内置类型。

http://docs.python.org/library/types.html

#5


3  

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

要明确在Python中考虑什么是“原始”并不容易。但是你可以列出并检查你想要的所有内容:

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

#6


0  

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'>

#7


0  

This works:

try:
    import builtins
except ImportError:
    import __builtin__ as builtins

def get_primitives():
    return list(filter(lambda x: not x.startswith('_'), dir(builtins)))

Python 3.6:

In [241]: get_primitives()
Out[241]: 
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'ModuleNotFoundError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'ZeroDivisionError',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'display',
 'divmod',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']

#1


32  

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

由于Python中没有原始类型,您自己必须定义您认为原始的:

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

#2


22  

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.

在Python中,一切都是对象;即使是内联和布尔。因此,如果用“原始”表示“不是对象”(因为我认为这个词在Java中使用),那么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:

如果你想知道一个给定的值(记住,在Python变量中没有类型,只有值可以)是int,float,bool或你认为是“原始”的任何类型,那么你可以这样做:

 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.

如果您还需要考虑子类化内置类型的类型,请查看内置的isinstance()函数。

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.

Python专家尝试编写代码,对发送的类型做出最小的假设。允许这是该语言的优势之一:它通常允许代码以意想不到的方式工作。因此,您可能希望避免编写在类型之间进行任意区分的代码。

#3


19  

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

正如每个人所说,python中没有原始类型。但我相信,这就是你想要的。

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

#4


6  

You may want to take a look at types module, that lists all python built-in types.

您可能需要查看types模块,它列出了所有python内置类型。

http://docs.python.org/library/types.html

#5


3  

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

要明确在Python中考虑什么是“原始”并不容易。但是你可以列出并检查你想要的所有内容:

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

#6


0  

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'>

#7


0  

This works:

try:
    import builtins
except ImportError:
    import __builtin__ as builtins

def get_primitives():
    return list(filter(lambda x: not x.startswith('_'), dir(builtins)))

Python 3.6:

In [241]: get_primitives()
Out[241]: 
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'ModuleNotFoundError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'ZeroDivisionError',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'display',
 'divmod',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']