python中from module import * 的一個坑

來源:互聯網
上載者:User
但還有另外一個問題 - 你以為你修改了某個變數,其實,被from module import *後的那個並沒有被更新,非常危險,因為程式有可能還可以正常運行, 只不過結果錯了,到了production才被發現就比較慘了。

舉個例子:

你定義了一些變數在base模組中:

# reference data typeclass Demo: def __init__(self, name):  self.name = namedemo = Demo('Demo')# primitive typefoo = 1

然後在一個模組中用from module import 的方式讀它:

from base import *def read():    print 'reference data id: ' + str(id(demo))    print 'reference data value : ' + demo.name    print 'primitive data id: ' + str(id(foo))    print 'primitive data value: ' + str(foo)

在另外一個模組中寫它:

import basedef write(): print "\nOriginal:" print "Original reference data id: " + str(id(base.demo)) base.demo.name = "Updated Demo" # this will reflect that change #base.demo = base.Demo("Updated Demo") # this won't relfect the change print "Original data id: " + str(id(base.foo)) base.foo = 1000 print "Original data id after assignment: " + str(id(base.foo))

然後先寫,後讀,看寫的內容是否有效:

import readimport writeprint "before write"read.read()write.write()print "\nafter write"read.read()

結論是沒有,原因是:

當你用from module import時,其實是copy了一份reference或者pointer,指向一份記憶體,var和module.var都指向同一份記憶體
當你修改module.var時,其實你是讓它指向了另外一份記憶體,此時var和module.var指向的是不同的記憶體
所以,雖然module.var的值變了,var還是指向原來那份記憶體,原來的值
這個對於object,比較容易理解,你可以直接修改object裡的值,這個是有效,但是當你指向另外一個object時就無效了。 對於primitive類型來講,其實也是一個道理,因為每次賦值,都是讓其指向一個不同的記憶體位址,而不是inplace修改已有的那份記憶體 - 這個很容易驗證:

In [1]: a = 10In [2]: id(a)Out[2]: 20429204In [3]: a = 100In [4]: id(a)Out[4]: 20430108

所以,建議是除非是一個quick and dirty的指令碼,否則不要使用from module import *!

例子: https://github.com/baiyanhuang/blog/tree/master/arena/python/from_module_import

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.