-1

I am using pympler's muppy module to retrieve information about the memory.
What I would like to do is to be able to filter down the results by object type, like so:

objects = [o for o in objects if isinstance(o, Type)]

This works if in the code I specify the type, (e.g. Type=str) but I would also like to be able to ask users to write down the types they want to filter down. Except that when I do that, it will be stored as a string, which would give me the following:

isinstance(test, 'int')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types

My question is, how can I get a string representing a type ('int', 'tuple', 'list', etc...) and transform it into a variable holding the type itself, so that I can use it as argument of the isinstance function.

Thank you for your help,

user171635
  • 21
  • 3

1 Answers1

2

Try using:

builtin_types = {t.__name__: t for t in __builtins__.__dict__.values() if isinstance(t, type)}
objects = [o for o in objects if isinstance(o, builtin_types[Type])]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Thank you! I noticed that for python 3 we should do: import builtins builtin_types = {t.__name__: t for t in builtins.__dict__.values() if isinstance(t, type)} – user171635 Dec 16 '19 at 12:14