开发者

Using a variable for an import

I have the following pattern:

databasename = "mydatabase"
import d开发者_如何学编程atabasefunctions

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.


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"


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):
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜