from pprint import *
def allvars_bad():
fake_temp_var = 1
d = dict(globals())
d.update(locals())
return d
def foo_bad():
x = 5
return allvars_bad()
def foo_good():
x = 5
fake_temp_var = "good"
d = dict(globals())
d.update(locals())
return d
pprint (foo_bad(), width=50)
pprint (foo_good(), width=50)
출력 : 여기에 코드입니다 (난 단지 SO 멋지게 출력 형식을 pprint을 사용) 두 번째 출력에, 우리는 fake_temp_var
을 덮어 것을
{'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d316ec>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': 'temp.py',
'__name__': '__main__',
'__package__': None,
'allvars_bad': <function allvars_bad at 0xb7d32b1c>,
'd': <Recursion on dict with id=3084093748>,
'fake_temp_var': 1,
'foo_bad': <function foo_bad at 0xb7d329cc>,
'foo_good': <function foo_good at 0xb7d32f0c>,
'isreadable': <function isreadable at 0xb7d32c34>,
'isrecursive': <function isrecursive at 0xb7d32c6c>,
'pformat': <function pformat at 0xb7d32bc4>,
'pprint': <function pprint at 0xb7d32b8c>,
'saferepr': <function saferepr at 0xb7d32bfc>}
{'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d316ec>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': 'temp.py',
'__name__': '__main__',
'__package__': None,
'allvars_bad': <function allvars_bad at 0xb7d32b1c>,
'd': <Recursion on dict with id=3084093884>,
'fake_temp_var': 'good',
'foo_bad': <function foo_bad at 0xb7d329cc>,
'foo_good': <function foo_good at 0xb7d32f0c>,
'isreadable': <function isreadable at 0xb7d32c34>,
'isrecursive': <function isrecursive at 0xb7d32c6c>,
'pformat': <function pformat at 0xb7d32bc4>,
'pprint': <function pprint at 0xb7d32b8c>,
'saferepr': <function saferepr at 0xb7d32bfc>,
'x': 5}
참고하고, x는 선물; 첫 번째 출력은 allvars_bad
범위 내의 로컬 변수 만 포함합니다.
그래서 전체 변수 범위에 액세스하려는 경우 locals()를 다른 함수 안에 넣을 수 없습니다.
나는 어떤 종류의 프레임 개체가 있다고 의심했지만, 그 프레임을 찾지 못했습니다.
이것은 당신의 사양에 작동 , 저는 믿습니다 :
def allvars_good(offset=0):
frame = sys._getframe(1+offset)
d = frame.f_globals
d.update(frame.f_locals)
return d
def foo_good2():
a = 1
b = 2
return allvars_good()
->
{'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d6474c>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': 'temp.py',
'__name__': '__main__',
'__package__': None,
'a': 1,
'allvars_bad': <function allvars_bad at 0xb7d65b54>,
'allvars_good': <function allvars_good at 0xb7d65a04>,
'b': 2,
'foo_bad': <function foo_bad at 0xb7d65f44>,
'foo_good': <function foo_good at 0xb7d65f7c>,
'foo_good2': <function foo_good2 at 0xb7d65fb4>,
'isreadable': <function isreadable at 0xb7d65c6c>,
'isrecursive': <function isrecursive at 0xb7d65ca4>,
'pformat': <function pformat at 0xb7d65bfc>,
'pprint': <function pprint at 0xb7d65bc4>,
'saferepr': <function saferepr at 0xb7d65c34>,
'sys': <module 'sys' (built-in)>}
왜 그렇게하고 싶습니까? 기회는 무엇이든 할 수있는 더 좋은 방법입니다. –
나는 그 발췌 문장이 그것을 명확하게 만들 것이라고 생각했다. 문자열 내부 변수를 보간하고 싶습니다. 꼭 좋은 방법이있을 수 있습니다. 언제든지 대답으로 제안하십시오. –
죄송합니다, 발췌 문장은 설명하지 않습니다 ** ** 왜 그런 일이 필요합니다. 또한 매개 변수는 단순히 로컬이므로 별도의 범위가 아닙니다. –