Cindy Almighty
Cindy Almighty

Reputation: 933

String representation of type in Python

I wish to use a type function in an eval statement, so I need just the string representation of that function. For example:

print(type("cow"))
<class 'str'>

Here I need it to output 'str'. But when I try:

type("cow").__str__()
TypeError: descriptor '__str__' of 'str' object needs an argument
type("cow").__repr__()
TypeError: descriptor '__repr__' of 'str' object needs an argument

Curiously, Jupyter notebook prints it correctly if that is the last line in the cell.

Why is this error happening? What is the correct way to obtain just the Type string?

Upvotes: 1

Views: 771

Answers (2)

CristiFati
CristiFati

Reputation: 41116

Given the question ambiguity, print(type("cow")) is kind of misleading. Is cow:

  • The string "cow"
  • A variable named cow (that by coincidence happens to be a string in this case)

Anyway here's a way that works for both:

>>> cow = "Moo!!"
>>>
>>> # Variable
...
>>> cow.__class__.__name__
'str'
>>> # String literal
...
>>> "cow".__class__.__name__
'str'

For more details, check [Python 3.Docs]: Built-in Types - Special Attributes.

Upvotes: 2

tomjn
tomjn

Reputation: 5389

Maybe you want

type("cow").__name__

?

Upvotes: 4

Related Questions