Get importer module from imported module
Duncan Booth
duncan.booth at invalid.invalid
Mon Feb 7 07:15:46 EST 2005
dody suria wijaya wrote:
> "import a" inside b would not solve the problem, since there
> are many "module a" and module b does not know beforehand
> which module had imported it.
Ok, I understand now what you are trying to achieve, but there isn't any
concept relating a module back to the first module which tried to import
it. Instead you'll have to specify the relationship yourself.
How about this:
> #Module c
import sys
food_no = sys.argv[1]
m = __import__(food_no)
goodie = b.Salty(m)
> #Module b
...
def Salty(module):
class Food(SaltyMixIn,module.Main): pass
return Food()
...
In fact, it looks like the importing isn't really something module c should
be concerned about. I haven't tested the following code (so it will have
bugs), but it should give you some ideas. It remembers classes it has
created so as not to duplicate them, and it also gives each class a
sensible name.
> #Module c
import sys
food_no = sys.argv[1]
goodie = b.Salty(food_no)
> #Module b
...
import new
Classes = {}
def makeFood(classname, food, mixin):
m = __import__(food)
main = m.Main
if (mixin, main) in Classes:
return Classes[mixin, main]()
newclass = new.classobj(classname + '_' + food, (mixin, main), {})
Classes[mixin, main] = newclass
return newclass
def Salty(food):
return makeFood('Salty', food, SaltyMixIn)
...
More information about the Python-list
mailing list