Daan Timmer
Daan Timmer

Reputation: 15047

retrieve the Package.Module.Class name from a (Python) class/type

Right, say I've got this structure: (Which I happen to actually have)

Now I want to get this whole structure (Interface.Test.Test) as a string stored somewhere. I know I can use type(myTestObjectInstance) or myTestObjectInstance.__class__ But that retrieves me a type object, which prints like <class 'Interface.Test.Test'>

But from there on I don't know how to get the actual structure part. I can of course just parse the string, but I suppose there is a more easy way of doing that?

[edit]
Larsmans has provided an answer but it doesn't fully answer what I would like to do:
His answer will not work if all I've got provided is that type object itself (type(myTestObjectInstance)

Upvotes: 0

Views: 170

Answers (1)

Fred Foo
Fred Foo

Reputation: 363587

Using inspect.getmodule you can (sometimes) find the module in which an object was defined, e.g.

>>> from collections import defaultdict
>>> import inspect
>>> inspect.getmodule(defaultdict)
<module 'collections' from '/usr/lib/python2.6/collections.pyc'>

The module name can be found using __name__. Note that the defining module need not be the one you imported from due to re-exports:

>>> from scipy.sparse import csr_matrix
>>> inspect.getmodule(csr_matrix).__name__
'scipy.sparse.csr'

Upvotes: 1

Related Questions