Python中的eval函数

代码版本:3.6.3    文档:3.6.6eval()

 eval()是Python内置函数,点进去是这样的

def eval(*args, **kwargs): # real signature unknown
    """
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    """
    pass

 pycharm提示是这样的

eval evalts

eval()接收一个字符串格式的表达式参数,和两个可选参数globals和locals,如果给的话,global是必须是字典,locals可以是任何映射对象。返回表达式的结果。

可选参数其实是给一个寻找的范围,如果给的话,用位置传参格式,不能用关键字传参格式。如果不给定,则从locals()和globals()里寻找内容,返回表达式的结果。

 

例子:

没有globals和locals参数的:

def f():
    pass


class A:
    pass


a = A()

my_list = ['1', '1.0', '[2]', '(1,)', '{1,}', '{"k":"v"}', 'f', 'A', 'a']
for i in my_list:
    da = eval(i)
    print(da, type(da))


# 结果:
# 1 <class 'int'>
# 1.0 <class 'float'>
# [2] <class 'list'>
# (1,) <class 'tuple'>
# {1} <class 'set'>
# {'k': 'v'} <class 'dict'>
# <function f at 0x000001DB6D376048> <class 'function'>
# <class '__main__.A'> <class 'type'>
# <__main__.A object at 0x000001DB6D98C320> <class '__main__.A'>

 

有参数的:

def fa():
    print('func a is run')


def fb():
    print('func b is run')


g = {'fa': fb, 'fb': fa}

eval('fa')()
eval('fa', g)()


# 结果:
# func a is run
# func b is run

 

一直说是表达式,举个例子

def fa():
    return 3


g = {'a': 1}

print(eval('print(1)'))
print(eval('fa()'))
print(eval('a+1', g))


# 结果:
# 1
# None
# 3
# 2

 

注意,第一个参数必须是可执行的表达式,如果只是一个普通的字符串,那就报错

eval('tomorrow')
# Traceback (most recent call last):
#   File "E:x/x.py", line 1, in <module>
#     eval('tomorrow')
#   File "<string>", line 1, in <module>
# NameError: name 'tomorrow' is not defined


eval('see you')
# Traceback (most recent call last):
#   File "E:x/x.py", line 10, in <module>
#     eval('see you')
#   File "<string>", line 1
#     see you
#           ^
# SyntaxError: unexpected EOF while parsing

 

可选参数传入的话要注意,会改变你传入的字典本来的内容。文档:

If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed.

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值