Подтвердить что ты не робот

Как проверить, является ли тип переменной примитивным?

Я не знаю, как проверить, является ли переменная примитивной. На Java это так:

if var.isPrimitive():
4b9b3361

Ответ 1

Поскольку в Python нет примитивных типов, вы сами должны определить, что вы считаете примитивным:

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

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

Но тогда вы тоже рассматриваете этот примитив:

class MyStr(str):
    ...

?

Если нет, вы можете сделать это:

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

Ответ 2

В Python все является объектом; даже ints и bools. Поэтому, если под "примитивным" вы подразумеваете "не объект" (как я думаю, это слово используется в Java), то в Python таких типов нет.

Если вы хотите узнать, задано ли заданное значение (помните, что в переменных Python нет типа, только значения), это int, float, bool или любой тип, который вы считаете "примитивным", тогда вы можете сделать:

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

(Нужно ли упоминать, что типы также являются объектами с их собственным?)

Если вам также необходимо учитывать типы, которые подклассифицируют встроенные типы, проверьте встроенную функцию isinstance().

Гуру Python пытается написать код, который делает минимальные предположения о том, какие типы будут отправлены. Разрешение этого является одной из сильных сторон языка: он часто позволяет коду работать неожиданными способами. Поэтому вы можете избежать написания кода, который делает произвольное различие между типами.

Ответ 3

Как говорит каждый, в 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

Возможно, вам захочется взглянуть на модуль types, в котором перечислены все встроенные типы python.

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

Ответ 5

Нелегко сказать, что считать "примитивным" в Python. Но вы можете составить список и проверить все, что хотите:

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

Ответ 6

Это работает:

try:
    import builtins
except ImportError:
    import __builtin__ as builtins

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

Python 3.6:

 
 In [241]: get_builtins() 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'] In [241]: get_builtins() 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']

Ответ 7

Если это помогает,

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