Python/Analysis to Python
[eval, exec] : 문자열을 코드로 실행하는 함수
샰롯
2022. 5. 30. 21:34
eval()
Signature: eval(source, globals=None, locals=None, /)
Docstring: 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.
"""
Type: builtin_function_or_method
eval()
- 문자열을 코드로 변경하는 함수
→ 파이썬 내장 함수(builtin_function)
→ 결과값을 반환한다. - 문자열로 입력된 바인딩 실행 불가능
- globals =
→ ? - locals =
→ ?
사용 예제:
print(eval('2+1'))
3
# 연산자를 문자열로 리스트에 저장해 사용할 수 있다.
first_num = 1
last_num = 2
operator_list = ['+', '-', '*', '/', '**', '//', '%']
for operator in operator_list:
print(f'{first_num} {operator} {last_num} =',
eval(f'{first_num}{operator}{last_num}'))
1 + 2 = 3
1 - 2 = -1
1 * 2 = 2
1 / 2 = 0.5
1 ** 2 = 1
1 // 2 = 0
1 % 2 = 1
# 코드를 문자열로 리스트에 저장하여 사용할 수 있다.
function_list = [
'[i for i in range(1, 10+1)]',
'sum([i for i in range(1, 10+1)])',
'sum(range(1, 10+1))',
]
for function in function_list:
print(eval(function))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
55
55
SyntaxError: invalid syntax
# 문자열로 바인딩 및 입력된 코드 실행
eval('num_list = [i for i in range(1, 10+1)]')
print(num_list)
Traceback (most recent call last):
File ~/#####/#####/#####/#####/#####/#####/#####/#####/#####.py:#### in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
Input In [#] in <cell line: 1>
eval('num_list = [i for i in range(1, 10+1)]')
File <string>:1
num_list = [i for i in range(1, 10+1)]
^
SyntaxError: invalid syntax
- 문자열로 코드 실행 및 바인딩은 exec() 함수에서 사용 가능하다.
exec()
Signature: exec(source, globals=None, locals=None, /)
Docstring: Execute the given source in the context of globals and locals.
"""
The source may be a string representing one or more Python statements 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.
"""
Type: builtin_function_or_method
exec()
- 문자열을 코드로 변경하는 함수
→ 파이썬 내장 함수(builtin_function)
→ 반환값은 없다. - 문자열로 입력된 바인딩 실행 가능
→ 문자열로 입력된 바인딩이 가능하다. - globals =
→ ? - locals =
→ ?
사용 예제:
print(exec('2+1'))
None
# 문자열로 바인딩 및 입력된 코드 실행
exec('num_list = [i for i in range(1, 10+1)]')
print(num_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- eval() 함수와 달리 return값이 없으며, 입력된 코드를 실행만 하는 기능을 한다.