Question

I have a library class where depending how it's imported, a method that relies on the self.__module__ for identification changes behavior - depending on if I import it relatively or absolutely. Is there a way to force the self.__name__ attribute of a class to return itself absolutely?

I realize one solution would be to force everyone to import the subclasses in the same way, but was wondering if there was a way to force it from the library's standpoint.

Summarized Structure

I have a module in a library

project/
    mylib/
        foo.py
            LibraryClass
            def get_name(self):
                return "%s.%s.%s" % \
                    (self.__module__, self.__class__.__name__, self.some_init_property)
    prog/
        utils.py
            fooClass(LibraryClass)
        bar.py
            def some_func()
               #see below

In mylib, I have an importer import all subclasses of LibraryClass via a the string of the classname in our django project's settings file.

Basically, the behavior we're seeing is depending on how you import. So there are two behaviors I'm observing in bar.py:

def some_func_absolute():
    from prog.utils import fooClass
    f = fooClass("lalala")
    print f.get_name()
    #prints prog.utils.fooClass.lalala

Versus

 def some_func_relative():
    from utils import fooClass
    f = fooClass("lalala")
    print f.get_name()
    #prints foo.fooClass.lalala
Was it helpful?

Solution

I suspect that the right thing here is to never have parent/child directories in the python path. I also suspect that this might not be possible given that you do. Depending what you're doing, maybe you could use .__file__ instead which should still be consistent no matter how it's imported?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top