For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about x.__class__.__name__
, but is there a simple method to get the package and module?
Consider using the
inspect
module which has functions likegetmodule
which might be what are looking for:__module__
would do the trick.Try:
This site suggests that
__package__
might work for Python 3.0; However, the examples given there won't work under my Python 2.5.2 console.Since the interest of this topic is to get fully qualified names, here is a pitfall that occurs when using relative imports along with the main module existing in the same package. E.g., with the below module setup:
Here is the output showing the result of importing the same module differently:
When hum imports bar using relative path, bar sees
Baz.__module__
as just "baz", but in the second import that uses full name, bar sees the same as "foo.baz".If you are persisting the fully-qualified names somewhere, it is better to avoid relative imports for those classes.
Here's one based on Greg Bacon's excellent answer, but with a couple of extra checks:
__module__
can beNone
(according to the docs), and also for a type likestr
it can be__builtin__
(which you might not want appearing in logs or whatever). The following checks for both those possibilities:(There might be a better way to check for
__builtin__
. The above just relies on the fact that str is always available, and its module is always__builtin__
)The provided answers don't deal with nested classes. Though it's not available until Python 3.3 (PEP 3155), you really want to use
__qualname__
of the class. Eventually (3.4? PEP 395),__qualname__
will also exist for modules to deal with cases where the module is renamed (i.e. when it is renamed to__main__
).For python3.7 I use:
Getting: