Confused about imports and evals -- Python -
say have 2 scripts, script1 , script2.
script1 defined as:
class foo(object): def __init__(self, name): self.name = name class bar(object): def __init__(self, name): self.name = name def test(givenstring): return eval(givenstring)
and script2 defined as:
from .script1 import test x = "foo('me')" print test(x)
script2's print statement test(x)
tells me have foo
object, doesn't make sense me because imported test
script1, not foo
. looked @ eval
documentation didn't clear me. how possible foo
object created when never imported class foo
?
eval()
uses globals of module executed in. test
'lives' in script1
global namespace, expression executed eval()
uses same namespace function , can resolve foo
, bar
, test
.
importing function not alter namespace; globals test
don't change merely being called script2
. if did, imports in script1
also need imported script2
, each , every function ever wanted use. incredibly impractical.
you can see globals functions import; print test.func_globals
show exact namespace of script1
.
Comments
Post a Comment