Getting module path string from a class instance

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Nov 13 08:19:10 CET 2012


On Tue, 13 Nov 2012 06:38:31 +0000, Some Developer wrote:

> I'm trying to find a way to get a string of the module path of a class.
> 
> So for instance say I have class Foo and it is in a module called
> my.module. I want to be able to get a string that is equal to this:
> "my.module.Foo". I'm aware of the __repr__ method but it does not do
> what I want it to do in this case.
> 
> Can anyone offer any advice at all?

py> from multiprocessing.pool import Pool
py> repr(Pool)
"<class 'multiprocessing.pool.Pool'>"

Seems pretty close to what you ask for. You can either pull that string 
apart:

py> s = repr(Pool)
py> start = s.find("'")
py> end = s.rfind("'")
py> s[start+1:end]
'multiprocessing.pool.Pool'

or you can construct it yourself:

py> Pool.__module__ + '.' + Pool.__name__
'multiprocessing.pool.Pool'


-- 
Steven


More information about the Python-list mailing list