I have the following pattern:
databasename = "mydatabase"
import databasefunctions
and in databasefunctions I have the following method.
def checkStatusOfDatabase(database=databasename):
I however get an error saying: NameError: name 'databasename' is not defined on the line defining checkStatusOfDatabase.
I could of course just move the definition of databasename inside the databasefunctions module, but that would not be suitable in my design. How else can I achieve that the databasename defined in the main module is utilized as the default in any imported modules.
-
Out of curiosity, why are you unable to do the definition in the databasefunctions module?aodj– aodj2011年01月21日 11:25:53 +00:00Commented Jan 21, 2011 at 11:25
-
Not an exact duplicate, but this should answer your question to some extent: stackoverflow.com/questions/67631/…viraptor– viraptor2011年01月21日 11:28:29 +00:00Commented Jan 21, 2011 at 11:28
-
I would like to have all the parameter values right in the beginning of my main module (because I modify them a lot) and not hidden away in different imported modules.David– David2011年01月21日 11:29:28 +00:00Commented Jan 21, 2011 at 11:29
-
@viraptor. That answer is related but does not help me as I am already definining the variable before I import, but that does not help.David– David2011年01月21日 11:31:15 +00:00Commented Jan 21, 2011 at 11:31
-
sorry, I misunderstood your question - I read it as if you were trying to load a module called "mydatabase"... You're right it does not answer the question.viraptor– viraptor2011年01月21日 11:39:23 +00:00Commented Jan 21, 2011 at 11:39
2 Answers 2
You cannot (and should not) do that; doing so would make it impossible to just import databasefunctions without the main module. However, you can implement a default like this:
# databasefunctions
DEFAULT_NAME = ""
def checkStatusOfDatabase(database=DEFAULT_NAME):
# main
import databasefunctions
databasefunctions.DEFAULT_NAME = "mydatabase"
4 Comments
from __main__ import databasename in the databasefunctions module. But I absolutely agree that you should not, and your alternative is the Right Way.DEFAULT_NAME = "mydatabase" only makes the name DEFAULT_NAME refer to something different within your main module. The assignment databasefunctions.DEFAULT_NAME = "mydatabase", on the other hand, changes the meaning of DEFAULT_NAME within the databasefunctions module. It's a subtle distinction, and surprising if you're used to other languages, like C, where assignments modify objects.You can use the __builtin__ module
import __builtin__
__builtin__.foo = 'bar'
This will then be accessible from all other modules when you do a similar access method. You could use this and do this:
import __builtin__
dbName = __builtin__.get('foo', 'ham') # dictionary access with default return
def checkStatusOfDatabase(database=dbName):
...