205

I want to avoid calling a lot of isinstance() functions, so I'm looking for a way to get the concrete class name for an instance variable as a string.

Any ideas?

1
  • 2
    This is NOT a duplicate of a question that got me here. I'm reading the "Concrete Objects Layer" documentation for Python 3. That documentation describes C-level mappings with types that are lower-level than the regular class name. So, for example, the documentation describes a "PyLongObject". I'd like to know how to get this low-level name given an arbitrary object. Commented Jun 17, 2018 at 18:59

3 Answers 3

354
 instance.__class__.__name__ 

example:

>>> class A(): pass >>> a = A() >>> a.__class__.__name__ 'A' 
Sign up to request clarification or add additional context in comments.

5 Comments

I prefer: type(instance).__name__
What if you don't want to instantiate the class? can you just get the name of the class? (without the object)
For class A, use the following: A.__name__
Is there a way to get it with the import path? For example, str(type(foo)) == "<class 'never.gonna.give.youup'>" but type(foo).__name__ == "youup". How do I get never.gonna.give.youup?
For path you can use type(foo).__module__
35
<object>.__class__.__name__ 

Comments

9

you can also create a dict with the classes themselves as keys, not necessarily the classnames

typefunc={ int:lambda x: x*2, str:lambda s:'(*(%s)*)'%s } def transform (param): print typefunc[type(param)](param) transform (1) >>> 2 transform ("hi") >>> (*(hi)*) 

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

2 Comments

+1. An 'is' test on the class object itself will be quicker than strings and won't fall over with two different classes called the same thing.
Sadly, this falls flat on subclasses, but +1 for the hint to "real" OOP and polymorphism.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.