Foobard
Foobard

Reputation: 80

is there any easy way to convert output of the type() function in python to string?

I'm trying to write a function that guesses a type of a variable represented as a string. So if I've got a variable of some type then in order to find out what type of a variable it is I can use python's type() function like this type(var). But how do I concisely and pythonicaly convert the output of this function into a string so that the output would be like 'int' in case of the integer, 'bool' in case of the bool etc. The only way I see I can do this is first use str(type(var)) and then use a regular expression to strip the part indicating the type.

So basically I could write a simple type guessing python function as follows:

import ast
import re


def guess_type(var):
    return re.findall('\w+',str(type(ast.literal_eval(var))))[1]

where var is of type str. But my question is "Is there a more simple way to get the same result?"

Speaking of performance:

In [156]: %timeit guess_type
10000000 loops, best of 3: 28.1 ns per loop.

Upvotes: 0

Views: 727

Answers (2)

zimmerrol
zimmerrol

Reputation: 4951

What are you actually trying to do? If you just want to get the name of the class of the object you could use:

type(var).__name__

This will give you the name of the class of the object var.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799430

>>> type(0).__name__
'int'
>>> type('').__name__
'str'
>>> type({}).__name__
'dict'

Upvotes: 2

Related Questions