Modifying a variable in a module imported using from … import *

前端 未结 3 1336
野趣味
野趣味 2021-01-11 19:15

Consider the following code:

#main.py
From toolsmodule import *
database = \"foo\"

#toolsmodule
database = \"mydatabase\"

As it seems, thi

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 19:54

    Pythons variable names are just labels on variables. When you import * all those labels are local and when you then set the database, you just replace the local variable, not the one in toolsmodule. Hence, do this:

    toolsmodule.py:

    database = "original"
    
    def printdatabase():
       print "Database is", database
    

    And then run:

    import toolsmodule
    toolsmodule.database = "newdatabase"
    toolsmodule.printdatabase()
    

    The output is

    Database is newdatabase
    

    Note that if you then from ANOTHER module ALSO did an import * the change is not reflected.

    In short: NEVER use from x import *. I don't know why all newbies persist in doing this despite all documentation I know of says that it's a bad idea.

提交回复
热议问题