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.

6
  • 1
    Could you explain what you're actually trying to achieve, and why? Commented Oct 14, 2016 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? Commented Oct 14, 2016 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. Commented Oct 14, 2016 at 21:33
  • This is close to what I need. I think I may have to just list it afterall as you mentioned. stackoverflow.com/questions/6391694/… Commented Oct 14, 2016 at 21:53
  • "Basically anything which has a repr that looks like <type X> instead of <class X>." - that difference completely goes away in Python 3, and it only exists in Python 2 for historical reasons. Commented Oct 14, 2016 at 22:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Or tested_object.__class__.__module__ == '__builtin__' ?
Indeed that is better!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.