Python import and module scoping (specifically sys.ps1) -
why following not work:
from sys import ps1 ps1 = 'something else '
but does?
import sys sys.ps1 = 'something else '
if run simple test
import sys sys import ps1 ps1 = 'something else' sys.ps1 = 'something else'
the first assignment doesn't work, second does. id() both ps1 , sys.ps1 same, should refer same thing, right?
the short version is: assignment doesn't mutate in python, rebinds names. rebinding different name, happens bound reference same string sys.ps1
doesn't affect sys.ps1
in way.
let's go through step step:
from sys import ps1
this imports sys
(but doesn't bind name sys
in current globals), binds name ps1
in current globals same object sys
's ps1
.
ps1 = 'something else '
this rebinds name ps1
in current globals same object literal 'something else'
. there's no way possibly affect sys
module.
import sys
this imports sys
, , binds name sys
in current globals it.
sys.ps1 = 'something else '
this looks name sys
in current globals, getting reference sys
module, rebinds name ps1
in module same object literal 'something else '
.
or, putting in pseudo-python terms, instead of in english…
your first code sample this:
tempspace._sys = __import__('sys') globals.ps1 = tempspace._sys.ps1 del tempspace._sys globals.ps1 = 'something else '
your second this:
globals.sys = sys_modules.sys = __import__('sys') globals.sys.ps1 = 'something else '
here transcript of described in comments.
python 2.7.2 (default, jun 20 2012, 16:23:33) [gcc 4.2.1 compatible apple clang 4.0 (tags/apple/clang-418.0.60)] on darwin type "help", "copyright", "credits" or "license" more information. >>> import sys >>> sys import ps1 >>> id(sys.ps1) 4360831168 >>> id(ps1) 4360831168 >>> sys.ps1 = 'something else ' else ps1 '>>> ' else
sys.ps1
, ps1
have same id, because 2 different names reference same object.
and changing sys.ps1
not change ps1
.
Comments
Post a Comment