开发者

Using a variable for an import

开发者 https://www.devze.com 2023-02-06 03:53 出处:网络
I have the following pattern: databasename = \"mydatabase\" import d开发者_如何学编程atabasefunctions

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

精彩评论

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

关注公众号