eval,exec和ast.literal_eval的用法

时间:2019-10-21 22:52:29

标签: python exec eval

是否有import re import sqlite3 with sqlite3.connect(":memory:") as con: con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0) cursor = con.cursor() # ... cursor.execute("SELECT * from person WHERE surname REGEXP '^A' ") oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, tenantID) spt, err := adal.NewServicePrincipalToken(*oauthConfig, clientID, clientSecret, "https://storage.azure.com/") creds := azblob.NewTokenCredential(spt.OAuthToken(), nil) blobPipeline := azblob.NewPipeline(creds, azblob.PipelineOptions{}) url := azblob.NewContainerURL(*URL, blobPipeline) _, err := url.ListBlobsHierarchySegment(...) eval的实际用法?在实际使用中,我唯一看到的是是否将类似python对象的内容保存到文件中,并且没有被腌制或其他任何内容。

使用这些功能的实际非平凡用例是什么?我能够在文档中找到的唯一示例是:

exec

1 个答案:

答案 0 :(得分:0)

evalexec用于分别动态执行简单的Python表达式或更复杂的语句。

So, one practical example from the standard library, collections.namedtuple uses exec to dynamically define a __new__ method for the tuple subclass being returned:

# Create all the named tuple methods to be added to the class namespace

s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
# Note: exec() has the side-effect of interning the field names
exec(s, namespace)
__new__ = namespace['__new__']
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
    __new__.__defaults__ = defaults

有时候这是有道理的,但是,经验不足的程序员经常滥用它来编写不必要的动态代码,例如在应该使用listdict(或其他容器)的情况下动态创建一堆变量。