Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

knowing the caller of an import && exec question

0 views
Skip to first unread message

bussiere bussiere

unread,
Sep 7, 2010, 10:31:34 AM9/7/10
to pytho...@python.org
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

Bruno Desthuilliers

unread,
Sep 7, 2010, 10:48:31 AM9/7/10
to
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

0 new messages