Getting the name of something

From the Department of the Blindingly Obvious.

Recently, I had the need to get an informative name from a range of Python objects for generating a useful error message. Where problems started was that these objects could include classes (new-style and old), functions, lambdas and built-in types. And here the logic started getting tricky.

  • To get the name of the class of an object, you can use obj.__class__.__name__. But these could be the classes themselves.
  • Likewise, the class of primitive types (int, float, str, etc.) is type, which is uninformative
  • Functions have an attribute func_name, that could be useful
  • Lambda's don't have any useful attribute for this at all, of course, because they are anonymous functions.
  • Googling for a solution brings a whole host of overly complicated and incomplete answers.

The solution is easy: almost everything answers to __name__. So we can do this:

# variable is 'totype'
type_name = None
if hasattr (to_type, '__name__'):
   type_name = getattr (totype, '__name__')
   # lambdas and all others require name be explicitly supplied
   assert (type_name not in [None, '<lambda>']), \
      "type validator requires type name for lambda"