knowing the caller of an import && exec question

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Sep 7 10:48:31 EDT 2010


bussiere bussiere a écrit :
> i've got toto.py :
> 
> import titi
> def niwhom():
>      pass
> 
> and titi.py :
> 
> def nipang():
>       pass
> 
> how can i know in titi.py that's it's toto.py that is calling titi.py
> and the path of toto ?

You'd have to inspect the call stack. Not for the faint at heart...

> And
> 
> why :
> 
> bidule.py :
> class bidetmusique:
>          pass

<OT>
The naming convention is to capitalize class names, ie "Bidetmusique" or 
  "BidetMusique"
</OT>

<OT mode="even-more">
Heureusement qu'il n'y a pas grand monde ici pour comprendre le 
français, parce que comme nommage, ça bat des records, là !-)
</OT>

> 
> truc.py :
> X = __import__("bidule")
> 
> why exec("X.bidetmusique()") return none

exec doesn't "return" anything - it executes code in a given context, 
eventually modifying the context. Now given your above code, a new 
bidetmusique instance is indeed created, but since it's not bound to 
anything, it's immediatly discarded.

> and X.bidetmusique() return an object ?

cf above


> How could i do to make this string "X.bidetmusique()" return an object ?

exec is 99 time out of 10 (nope, not a typo) the wrong solution. You 
already found how to dynamically import a module by name (I mean, name 
given as as string), all you need know is to find out how to dynamically 
retrieve a module attribute given it's name as string. And the answer is 
"getattr":


# truc.py :
X = __import__("bidule")
cls = getattr(X, "bidetmusique")
obj = cls()
print obj

HTH




More information about the Python-list mailing list