【问题标题】:How to access to calling module namespace from called module in Python?如何从 Python 中的被调用模块访问调用模块命名空间?
【发布时间】:2014-12-12 10:31:26
【问题描述】:

我为 SQLite 制作了一个小型的 sql 渲染器/包装器。主要思路是这样写:

execute( 'select * from talbe1 where col1={param1} and col2={param2}' )

而不是

execute( 'select * from table1 where col1=? and col2=?', (param1,param2) )

代码如下:

import re
import sqlite3

class SQLWrapper():
    def __init__(self, cursor):
        self.cursor = cursor
    def execute(self, sql):
        regexp=re.compile(r'\{(.+?)\}')
        sqlline = regexp.sub('?',sql)
        statements = regexp.findall(sql)
        varlist = tuple([ eval(_statement) for _statement in statements ])
        self.cursor.execute(sqlline, varlist)
        return self
    def fetchall(self):
        return self.cursor.fetchall()

#usage example
db = sqlite3.connect(':memory:')
cursor = db.cursor()

wrap = SQLWrapper(cursor)

wrap.execute('create table t1(a,b)')
for i in range(10):
    wrap.execute('insert into t1(a,b) values({i}, {i*2})')

limit = 50
for line in wrap.execute('select * from t1 where b < {limit}').fetchall():
    print line

它可以工作,但是当我将类 SQLWrapper 移动到一个单独的模块(文件 sqlwrap.py)并导入它时,程序崩溃了:

Traceback (most recent call last):
  File "c:\py\module1.py", line 15, in <module>
    wrap.execute('insert into t1(a,b) values({i}, {i*2})')
  File "c:\py\sqlwrap.py", line 10, in execute
    varlist = tuple([ eval(_statement) for _statement in statements ])
  File "<string>", line 1, in <module>
NameError: name 'i' is not defined

即变量 i 在其他模块中不可见。如何克服?

【问题讨论】:

    标签: python sqlite namespaces eval


    【解决方案1】:

    这违反了大多数编程语言的正常范围规则。

    通常你不希望你调用的函数(或方法)神奇地用你自己的变量做事。这意味着,只有那些变量值 (!) 才能被调用的例程访问,您将其显式添加为参数。

    当您在第一个代码中(全部在一个模块中)将带有 i 的 for 循环移动到自己的函数中时,将遇到同样的问题 - 而 i 将是该函数的本地函数,并且对 SQLwrapper 不可见。

    范围规则有意将变量的访问权限限制为“在范围内”的变量,并且不授予对“超出范围”内容的访问权限。这样就完成了一些信息隐藏,降低了复杂性。

    这意味着在某些情况下会产生一些写入开销,但也可以通过抑制一些危险的做法和复杂性使程序更加节省。

    当您只打算使用 SQLite(或 MySQL)时,我会推荐类似的东西:

    execute( 'select * from table1 where col1=@param1 and col2=@param2', {'param1': param1, 'param2': param2} )
    

    因此,您有一个更易读和易于理解的版本,但没有您遇到的范围问题。 @-prefix 适用于 SQLite,据我所知,也适用于 MySQL——但它是特定于数据库的(遗憾的是,SQL 没有对其进行标准化)。在 sqlite3-module 的文档中,使用了另一个前缀 ':' 这也适用于 SQLite,但我不知道在哪个其他数据库上。

    见:sqlite3.Cursor.execute documentation

    顺便说一句,如果你想稍微减少你的写作开销,你可以写一些这样的包装器:

    def myExcecute(sql, **params):
       self.cursor.execute(sql, params)
    

    因此,您可以用更少的开销(和更少的括号)调用执行:

    myExecute( 'select * from table1 where col1=@param1 and col2=@param2', param1=param1, param2=param2 )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2021-02-17
      • 2021-05-19
      • 1970-01-01
      • 2019-03-22
      • 2014-01-26
      相关资源
      最近更新 更多