Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #33226

Re: Getting module path string from a class instance

Date 2012-11-13 07:54 +0000
From Some Developer <someukdeveloper@gmail.com>
Subject Re: Getting module path string from a class instance
References <mailman.3611.1352788721.27098.python-list@python.org> <50a1f46e$0$21742$c3e8da3$76491128@news.astraweb.com>
Newsgroups comp.lang.python
Message-ID <mailman.3613.1352793277.27098.python-list@python.org> (permalink)

Show all headers | View raw


On 13/11/2012 07:19, Steven D'Aprano wrote:
> 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'
>
>
Yeah I considered doing it this way but was wary of that method because 
of possible changes to the implementation of the __repr__ method in the 
upstream code. If the Django developers don't consider the __repr__ 
method a public API then it could change in the future breaking my code.

Of course this might not happen but I was hoping that there was a more 
generic way of doing it that did not rely on a certain implementation 
being in existence.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Getting module path string from a class instance Some Developer <someukdeveloper@gmail.com> - 2012-11-13 06:38 +0000
  Re: Getting module path string from a class instance Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-11-13 07:19 +0000
    Re: Getting module path string from a class instance Some Developer <someukdeveloper@gmail.com> - 2012-11-13 07:54 +0000
      Re: Getting module path string from a class instance Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-11-13 08:49 +0000
        Re: Getting module path string from a class instance Some Developer <someukdeveloper@gmail.com> - 2012-11-13 16:15 +0000

csiph-web