knowing the caller of an import && exec question

  • Thread starter bussiere bussiere
  • Start date
B

bussiere bussiere

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 ?

And

why :

bidule.py :
class bidetmusique:
pass


truc.py :
X = __import__("bidule")

why exec("X.bidetmusique()") return none
and X.bidetmusique() return an object ?

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

Regards and thanks
Bussiere
Eat the strawberry


Google Fan boy
 
B

Bruno Desthuilliers

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à !-)
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top