import parent

John Machin sjmachin at lexicon.net
Tue Feb 27 16:51:33 EST 2007


On Feb 28, 8:01 am, Greg Hoover wrote:
> How does one get access to the class that imported a module.  For example:
> foo imports bar -- how does bar access foo?

It shouldn't (in any language, not just Python). Callees should not in
general need to inspect their caller's data structures, and should not
uninvitedly alter their caller's data structures.

Given Foo is a class in module foo, in general it is preferred that
all operations on instances of Foo are carried out by methods of the
Foo class. Given oof is such an instance, and there is a documented
attribute zot, then you *may* pass oof as an arg to a
bar.some_function which may do things like
    if oof_arg.zot > 42:
        oof_arg.zot = 42
but this is not the preferred way.

Your subject "import parent" is "interesting". In what way is foo
considered to be the parent of bar?

foo imports bar which imports foo is called a "circular import".
Google in this newsgroup should dredge up some threads on this topic.
Bottom line: if what you want to do really would involve a circular
import, then you have a design mess -- foo+bar needs to be refactored
by moving functionality into different modules so that you don't get a
circular import. The result may be 1, 2 (different), or 3 modules.

If you tell us a bit more about what you are trying to do, we may be
able to help you more.

Cheers,
John




More information about the Python-list mailing list