0

I'm looking for a way to catch all the std type functions in Python (int, str, xrange, etc).

Basically anything which has a repr that looks like <type X> instead of <class X>. Here's a full list of all std types in Python 2: https://docs.python.org/2/library/stdtypes.html

If I use isinstance(X, type) or type(X) == type, it also catches all classes too, but I only want to detect type functions (or any names that's assigned to one of them (i.e. my_int = int).

The only idea that comes to my mind is checking if X.__name__ is in __builtins__ but I'm not sure if that's a clean nor correct solution.

Ehsan Kia
  • 1,475
  • 18
  • 26
  • 1
    Could you explain what you're actually trying to achieve, and why? – jonrsharpe Oct 14 '16 at 21:26
  • You can list them out explicitly ... `isinstance(x, (list, dict, set, unicode, str, ...))` or `x in {list, dict, set, unicode, str, ...}`. Out of curiosity, _why_ does it matter if something it a builtin type or not? – mgilson Oct 14 '16 at 21:28
  • I could list them all out since there's a finite number, but I was hoping to avoid that. I'm trying to catch any primitive type function. I don't think it's possible to create more primitive types in Python? So the only ones that will ever exist are builtins. Anything else will be a class. – Ehsan Kia Oct 14 '16 at 21:33
  • This is close to what I need. I think I may have to just list it afterall as you mentioned. http://stackoverflow.com/questions/6391694/check-if-a-variables-type-is-primitive – Ehsan Kia Oct 14 '16 at 21:53
  • "Basically anything which has a repr that looks like `` instead of ``." - that difference completely goes away in Python 3, and it only exists in Python 2 for historical reasons. – user2357112 Oct 14 '16 at 22:18
  • If you explained what you want to use this check for, it would be a lot easier to determine what you actually need to check. – user2357112 Oct 14 '16 at 22:19

2 Answers2

1

To check if a variable is a class or a builtin type, use inspect module.

>>> from inspect import isclass
>>> isclass(object)
True
>>> isclass(5)
False
>>> isclass(int)
True

Alternatively, try type(). Works both for Python 2.75 and 3.

>>> type(int) is type(type)
True

I didn't understand what you mean by "std type functions", I think they may be called just types.

Yaroslav Nikitenko
  • 1,695
  • 2
  • 23
  • 31
0

What you suggested seems good to me.

builtin = dir(__builtins__)
def is_builtin(tested_object):
    return tested_object.__class__.__name__ in builtin

Bear in mind, however, that built-in types can be overshadowed.

Update after comment from Rob:

def is_builtin(tested_object):
    return tested_object.__class__.__module__ == '__builtin__'
Ben Beirut
  • 733
  • 3
  • 12