From: kedra marbun on 6 Jul 2010 00:15 On Jul 5, 6:29 am, Steven D'Aprano <st...(a)REMOVE-THIS- cybersource.com.au> wrote: > On Sun, 04 Jul 2010 21:05:56 +0000, Tobiah wrote: > > foo.py: > > > import bar > > bar.show_importer() > > > output: > > > 'foo' or 'foo.py' or 'path/to/foo' etc. > > > Possible? > > I don't think so. Your question isn't even well-defined. Given three > modules: > > # a.py > import b > import d > > # b.py > import d > > # c.py > import a > import d > import b > print d.show_importer() > > and you run c.py, what do you expect d.show_importer() to return? > > And what about "from d import show_importer" -- does that count as > "importing d"? > > Why do you think that a module needs to know what other modules imported > it? I can't imagine why this would be necessary, what are you intending > to do with it? > > -- > Steven i guess he just likes to play things around, entertains his imagination, no need for practical reason for that
From: kedra marbun on 6 Jul 2010 00:25
On Jul 5, 4:05 am, Tobiah <t...(a)rcsreg.com> wrote: > foo.py: > > import bar > bar.show_importer() > > output: > > 'foo' or 'foo.py' or 'path/to/foo' etc. > > Possible? > > Thanks, > > Tobiah if what you mean by 'importer' is the one that really cause py to load the mod, then why not dynamically set it? foo.py ------ import bar, sys if '_importer' not in bar.__dict__: bar._importer = sys.modules[__name__] bar.py ------ def show_importer(): return _importer or you could borrow space from builtins. i don't know if it breaks any rule ;) foo.py ------ def set_importer(mod): bdict = (__builtins__.__dict__ if __name__ == '__main__' else __builtins__) if '_importer' not in bdict: bdict['_importer'] = {mod : sys.modules[__name__]} else: if mod not in bdict: bdict['_importer'][mod] = sys.modules[__name__] import bar set_importer(bar) |