user688635
user688635

Reputation:

Get the return of 'type' as human readable string

How do I get the variable part of type as a string?

ie:

>>> type('abc')
<type 'str'>
>>> type(1)
<type 'int'>
>>> type(_)
<type 'type'>

In each case here, I want what is inside single quotes: str, int, type as a string.

I tried using a regex against repr(type(1)) and that works, but that does not seem robust or Pythonic. Is there a better way?

Upvotes: 9

Views: 1295

Answers (4)

Michael Herrmann
Michael Herrmann

Reputation: 5013

How about ... .__class__.__name__?

>>> 'abc'.__class__.__name__
'str'
>>> a = 123
>>> a.__class__.__name__
'int'

Upvotes: 3

sampson-chen
sampson-chen

Reputation: 47367

Use the __name__ attribute:

>>> type('abc').__name__
'str'

Upvotes: 1

Jesse the Game
Jesse the Game

Reputation: 2628

You can get the name by type(1).__name__

Upvotes: 11

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251156

use the __name__ attribute of type object:

In [13]: type('abc').__name__
Out[13]: 'str'

In [14]: type(1).__name__
Out[14]: 'int'

Upvotes: 3

Related Questions