Re: Getting module path string from a class instance

Discussion in 'Python' started by Some Developer, Nov 13, 2012.

  1. On 13/11/2012 09:36, Dave Angel wrote:
    > On 11/13/2012 01:38 AM, 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?

    > So you have:
    >
    > import my.module
    > theclass = my.module.Foo
    > print tellme(theClass)
    >
    > and you want to know how to write tellme? Why not just change it to
    > take a string, and pass it "my.module.Foo" ?
    >
    > If you have stored the class away somewhere, and want to figure it out
    > from there, you could look at the __module__ attribute. that'll tell
    > you the module name, but not the class name.
    >
    >
    > If you're really asking how to get that string from an INSTANCE of the
    > class, then try the __class__ attribute of that instance.

    I'm actually writing a dynamic importer.

    Basically when the program starts it queries all the loaded modules for
    a certain package. It then stores the module and class information in a
    database and then when a certain view is called the specific data
    required is loaded by calling importlib.import_module('module.class').
    This then populates the view with the required data.

    Basically the idea is to be able to display any data required without
    having to tightly couple the view code to a specific model type.

    Thanks for the help.
    Some Developer, Nov 13, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Madni
    Replies:
    1
    Views:
    5,873
  2. Sridhar R
    Replies:
    14
    Views:
    1,382
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  3. gentlestone
    Replies:
    6
    Views:
    929
    Bruno Desthuilliers
    Oct 6, 2009
  4. Martin P. Hellwig
    Replies:
    1
    Views:
    367
    Martin P. Hellwig
    Mar 26, 2010
  5. Some Developer
    Replies:
    4
    Views:
    179
    Some Developer
    Nov 13, 2012
Loading...

Share This Page