11

Consider the following code:

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

#toolsmodule
database = "mydatabase"

As it seems, this creates one variable in each module with different content. How can I modify the variable inside toolsmodule from main? The following does not work:

toolsmodule.database = "foo"

3 Answers 3

19

Sounds like yet another of the multitude of good reasons not to use from toolsmodule import *.

If you just do import toolsmodule, then you can do toolsmodule.database = 'foo', and everything is wonderful.

Sign up to request clarification or add additional context in comments.

4 Comments

I know of this, but I use these variables a lot, I have long module names, and I would like to avoid the extra typing.
So make module names short: import longmodulename as sname. Now sname will refer to longmodulename.
If you don't want to type toolsmodule everytime, you can do the following: import toolsmodule as tm. This way you keep your namespace sane and save typing.
And if you really want to spam your main namespace with toolsmodule.*, just use both techniques together: import toolsmodule; from toolsmodule import *.
6

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.

Comments

2

Why don't you do it like that:

import toolsmodule
toolsmodule.database = "foo"
from toolsmodule import *  #bad idea, but let's say you have to..
print database #outputs foo

1 Comment

When I tried this, I believe I ended up not being able to modify the variable from inside toolsmodule anymore. This needs to be verified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.